0

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)

4
  • 4
    Have you looked into JSON Schema? Commented Aug 14, 2018 at 17:00
  • So, only the keys in the data object matter? Commented Aug 14, 2018 at 17:00
  • 1
    "...and I want to avoid checking if each property exists. (This is possible in other languages, hence this question)" Just because they expose a high-level API to do it doesn't mean they don't check that each property exists. I can't imagine any other way you'd do it than checking for the properties. Commented Aug 14, 2018 at 17:01
  • "JSON template" - You mean a schema? Commented Aug 14, 2018 at 17:02

3 Answers 3

3

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't kwow about JSON Schema, I'll look into it, and now I know there's no 'native' way of doing this in JS besides manual checking. This answers my question. thank you!
0

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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.