JSON Extensions for writing config files and parsing data
Published 11/6/2024
JSON is a rather simple format, this makes it easy to use, understand, and parse. But sometimes you need a bit more than that, let's look at some common JSON extensions.
EJSON
Extended JSON is exactly what it sounds like. This dialect of JSON supports additional data types like dates and even lets you add your own types.
Here's an example showing the difference between regular JSON and EJSON when it comes to serializing and re-parsing objects containing dates.
const EJSON = require('ejson')
const event = {
name: 'test',
created_at: new Date()
}
const stingifiedJSON = JSON.stringify(event)
const stingifiedEJSON = EJSON.stringify(event)
// stringified
console.log(stingifiedJSON) // {"name":"test","created_at":"2024-11-06T00:00:00Z"}
console.log(stingifiedEJSON) // {"name":"test","created_at":{"$date":1730851200000}}
// re-parsed
console.log(typeof JSON.parse(stingifiedJSON).created_at) // string
console.log(EJSON.parse(stingifiedEJSON).created_at instanceof Date) // true
This is extremely useful for re-parsing serialized data, for example when sending it over the network. EJSON is what MongoDB uses under the hood (in addition to BSON, a binary format of JSON).
Among the JSON extensions listed in this article, this is the only one that regular JSON is able to parse as well!
NDJSON
Newline-Delimited JSON is commonly used for streaming one JSON object at a time.
This is how it looks like:
{"name":"test","created_at":"2024-11-02T00:00:00Z"}
{"name":"test 2","created_at":"2024-11-04T00:00:00Z"}
{"name":"test 3","created_at":"2024-11-06T00:00:00Z"}
What's different to regular JSON is the lack of wrapping the data in an array and the lack of commas after each line (since it's newline delimited). This makes it a perfect candidate for streaming.
Apart from streaming JSON, I've also seen this format being used (together with EJSON) in NoSQL clients to export and import documents.
JSONC / JSON5
For the next one there's a variety of implementations each adding its own flavor. Let's look at JSON5 as it's the most complete one.
They all try to achieve the same goal: a human-readable, loosened JSON format for managing config files.
JSON5 allows you to add comments, trailing commas, line breaks, unquotes keys, among many other things.
{
// You can add comments!!
unquoted: '< unquoted keys!',
singleQuotes: 'I can use "double quotes" here',
lineBreaks: "Supports line breaks!\
No \\n's!",
}
As you can see, JSON extensions come in all shapes and sizes. Some are meant to be used by applications, others allow devs to more easily create config files. Next time you need to serialize/parse JSON, see if one of those extensions make sense for your use case!