Reputation: 547
I want to compare received JSON data to a JSON 'template', and if it differs in structure (not in data itself) then do something,like discarding that JSON.
Template:
{
"data":{
"id":"1",
"cmd":"34"
}
Succesfull Json:
{
"data":{
"id":"15",
"cmd":"4"
}
Unsuccesfull Json:
{
"data":{
"id":"15"
}
This is only an example, the JSON to evaluate is going to be larger, and I want to avoid checking if each property exists. (This is possible in other languages, hence this question)
Upvotes: 0
Views: 456
Reputation: 2519
I recently faced this problem as well. I needed to make some comparisons on some objects (should work for JSON as well). I wrote a package for doing this that might come in handy for people facing this issue in the future (bit late for the topic starter).
https://www.npmjs.com/package/js-object-compare
Upvotes: 0
Reputation: 946
I would recommend converting it to object JSON.parse()
, so you can use javascript API.
If your structure gets more robust in the future (more levels etc), you would be still able to do deep compares. Libraries like Immutable.js will come handy, as it used to compare complex states in React applications.
Upvotes: 0
Reputation: 1074168
It sounds like you're looking for JSON Schema or other similar tools.
JavaScript itself doesn't provide anything built-in to do this for you. So you'll need an already-written tool to do it (such as JSON Schema) or you'll have to do it yourself, checking the existence and (depending on how strict you want to be) type of each property in the received JSON. You can do that either after parsing or during parsing by hooking into the parsing process via a "reviver" function you pass into JSON.parse
, but either way is going to require doing the checks. (Given the inside-to-outside way JSON.parse
works, I suspect using a reviver for this would be quite hard though. Much better to use a recursive function on the parsed data afterward.)
Upvotes: 3