What JSON Structure to Use for Key-Value Pairs?

json

What JSON format is a better choice for key value pairs and why?

[{"key1": "value1"}, {"key2": "value2"}]

Or:

[{"Name": "key1", "Value": "value1"}, {"Name": "key2", "Value": "value2"}]

Or:

{"key1": "value1", "key2": "value2"}

The first variant seems more compact and more "semantically meaningful". The second variant seems more evenly structured which might help processing it. The 3rd variant seems even more semantic.

The key value pairs will be used to attach arbitrary data to some other item. The data must be serialized as JSON to round-tip it through a system.

Best Answer

Whether you choose the first or the third option depends on your use case. If you are modeling many different instances of the same type of thing, choose the first. For example, you have a list of people. If you are modeling many different attributes of one thing, choose the third. You can have repeated keys in the first format, but not in the third.

The second option is terrible, and I've yet to find an appropriate use case for it. The reason it's terrible, in addition to being more verbose, is that for single-level JSON, it breaks most libraries' automatic conversion to a dictionary/map. For deeply-nested JSON, it breaks the XPath-like query interface.

This makes it a pain to work with. And if you don't know your keys at compile time, you will want a dictionary or XPath interface, because you won't be able to convert it to a class. It may not seem like a big deal now, but the longer you have a data format, the harder it will be to change.