0

Is it possible to check if a json is 'valid', by valid I mean the same type: for example

{"name": "John Doe", "username": "jhndoe"}

and

{"name": "Jane Doe", "username": "jane12"}

would be the same, but

{"name": "Ann Onymouse", "username": "anon"}

and

{"name": true, "age": "24"}

wouldn't.

foxtdev
  • 161
  • 1
  • 15

1 Answers1

2

If you want to compare two objects to see if they have the same set of keys, you can do it like this:

if (JSON.stringify(Object.keys(yourFirstObject).sort()) == JSON.stringify(Object.keys(yourSecondObject).sort())){
    alert("Same set of keys!");
}

Note however, that the given JSON Object example in your question is invalid. If that was just a mistake, you can still use this code on valid JSON Objects.

Example:

var obj1 = {"name": "John Doe", "username": "jhndoe"};
var obj2 = {"name": "Jane Doe", "username": "jane12"};

if (JSON.stringify(Object.keys(obj1).sort()) == JSON.stringify(Object.keys(obj2).sort())){
    console.log("Same set of keys!");
}
NullDev
  • 6,739
  • 4
  • 30
  • 54
  • I started to write similar answer, but stopped on the third object that is invalid (thats what op says). So your answer to given question is not correct :-) – Flash Thunder Jan 08 '18 at 18:07
  • @FlashThunder The given example of a JSON Object in the question was invalid. This could have been a simple mistake made by OP which does not make my answer incorrect. I edited my answer to point that out. – NullDev Jan 08 '18 at 18:09