Skip to content
Back to Blog

Storing Multi-Line Strings in JSON with JSONLint

Rich Jones

Feb 9, 2017 10:45:00 AM

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:

  {
  "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 multiline strings in JSON. It's not the prettiest thing, but it is the simplest given the constraints of JSON.

Written By:

Rich Jones

Want to get our totally not sh*tty weekly newsletter?

Sometimes The Wayfarer is funny, sometimes insightful, but always the least spammy newsletter this side of Tatooine.