Skip to main content
Gun.io Home

Storing multi-line strings in JSON with JSONLint

JSON is an extremely rigid schema, which can be great, but it’s definitely not without its shortcomings. The largest of shortcoming, in my mind, is the inability to store multi-line strings in JSON. It is something that 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!

Rich Jones
Rich Jones
· 2 min read
Storing multi-line strings in JSON

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:

{
servers: {
servername.com: {
publicKey: [
—–BEGIN PUBLIC KEY—–,
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0VmDBbzXdgubV/X8JP9B,
rM/CqvXBey49BoYjk0ar4OA4LZnmD0A/pn6voPPe+DQC3ZpSFfkdZc5s/ij7edve,
ob+reWdGOQAQnDxaGQoFyru/2tz1lNfaVOBU71QcpG4kda4XDjbS62hOqebgkQ0X,
71ireglZeaJABvu6EFPFBwyr2ROmM1dq4rKtinpgUf9CTMPL/8yyitka+HsVZTuI,
HDpFFxv6xPntfjMrIIRUPieIjRSJcF9yrTVqDIIOO9J3KplphXLXhAHRAnX3ducD,
sZYe5yZZEdkS9Kx4P0INkyiqs9DFGwVnIMU07IuM1E+LqLVTqm46MVxzrjaAcyVC,
WDTtzkERgvvaG8elbjb6iiA9aijNHM/EK0f68mjme7s0CHn9GJg4TwwvSLb8LqCs,
cCKT11WAanE+SuAi0WinuaeFORwAFFXh7O5sS8At4woCNVsIZpFSWWiRBoZf5UBC,
SfK8v9AL58foDDiCGlWKcpoQN5KBDBCTBD+RiXgoCKS9daHGpmXfAFsWmcjpVzvs,
l24ei4Ue1jd7kj7Dlc8qtXQGZS1BhwDaIV4SQBGYKEBgTMExcsAtI9Sd1rtMFybO,
wdfGmZkQ7pcLqOgEzyUOma+vwhWlvtfQXavH5NEdAS+ahsf8SDAI0TQtihLxTvO5,
LLrORy0wclzv7V0s+6qoRuMCAwEAAQ==,
—–END PUBLIC KEY—–
]
}
}
}
view raw multiline.json hosted with ❤ by GitHub

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:

var publicKey = our_data.servers[‘servername.com’].publicKey.join(‘n’);
view raw multiline.js hosted with ❤ by GitHub

And that’s it! Now you can store multi-line strings in JSON. It may not be the prettiest or most elegant solution in the world, but given the constraints of JSON, we like to think it works pretty well.


Interested in working with Gun.io? We specialize in helping engineers hire (and get hired by) the best minds in software development.

Learn more