There a lot's of SO questions asking "how" to get unknown JSON keys from a JSON object, and I've done it plenty of times, but after starting to use JSON schema to start designing API request and responses, I am starting to question if having unknown or even dynamic keys that the JSON consumer has to be smart enough to know how to use.
For example, assume you are designing a simple graphing API for a bar graph. You could tell your consumer that you are just going to send them data in this format:
"data": {
"Sunday": 1,
"Monday": 2,
"Tuesday": 3,
"Wednesday": 4,
"Thursday": 5,
"Friday": 6,
"Saturday": 7
}
Technically, this is enough to create a graph where the labels on the x-axis are the keys in this JSON object, and the numbers are the scalars graphed on the y-axis. It's also technically dynamic, as you could create a whole new graph with the same pattern:
"data": {
"Jack": 1,
"Jill": 2,
"Alice" 3
}
While JSON allows for flexibility, I'm beginning to question the usability of this. It feels like the equivalent of treating variable names in a Java class as a way of sending information.
An alternative approach might be to define a datapoint
schema or something like this:
"data": [
{
"category": "Jack",
"value": 1
},
{
"category": "Jill",
"value": 2
},
{
"category": "Alice",
"value": 3
}
]
Additionally, this seems more extensible as well, as additional values can be added to the schema. However, it there is probably less marshaling and it's probably a bit easier to just use the unknown keys approach.
It just got me wondering, I have used unknown keys on the past, but they suddenly don't seem like the best approach.
- Are using unknown keys an intended use case for JSON? Or just a side affect that is being taken advantage of?
- Are there any best practices that promote or discourage the use of unknown keys?
- If there are any best practices for using unknown keys, under what conditions are they recommended?
So you do call out that unknown keys don't work for objects that are intended to be ordered, but does not answer whether there is a best practice under which they should be used.
– rhamilton Aug 25 '17 at 06:03