JSON is an extremely rigid schema. It's great when you’re trying to learn JSON, 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 to this JSON data and coding conundrum!
JSON multi-strings examples
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 JSON file example:
{ | |
"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-----" | |
] | |
} | |
} | |
} |
You can verify that this valid JSON with JSONLint.
Retrieving the JSON language to JSON new line
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'); |
And that's it! Now you can store multiline strings and get results in JSON single line. It's not the prettiest thing, but it is the simplest given the constraints of JSON.