Storing Multi-Line Strings in JSON

By Rich Jones

JSON is an extremely rigid schema. It's great, but it has a couple of shortcomings, the largest of which is the inability to store multi-line strings. This can be particularly annoying for storing things like structured text and public keys in JSON for later interaction with JavaScript code in the browser or on the server in Node.

Fortunately, there is a quick and hacky solution!

Example

Imagine that we have a list of servers and their associated public keys. To store that data as JSON, we could store it as an array of comma-separated string objects, which might look something like this:

You can verify that this valid JSON with JSONLint.

Then, to retrieve our text block, we just have to join them back together on the newline characters, which we can do like this:

And that's it! Now you can store multiline strings in JSON. It's not the prettiest thing, but it is the simplest given the constraints of JSON.