0

I'm having an issue comparing objects encoded and decoded to and from JSON

//Test data
var test_obj = {
    test:'value',
    t:3,
    x:[0,5,3]
};
var t = JSON.stringify(test_obj);
var t_prime = JSON.parse(t);

You'd think that test_obj === t_prime would return true, or perhaps test_obj == t_prime would return true, but this is not the case.

Why is this, and how can I verify that I get the same object to and from a javascript object to JSON?

timw4mail
  • 1,716
  • 2
  • 13
  • 16
  • possible duplicate of [How do you determine equality for two JavaScript objects?](http://stackoverflow.com/questions/201183/how-do-you-determine-equality-for-two-javascript-objects) – James Montagne Nov 03 '11 at 14:31
  • Can you compare your objects in json format? JSON.stringify(test_obj) === JSON.stringify(t_prime) – Vertigo Nov 03 '11 at 14:34
  • @Vertigo I suppose I could, that's probably most reliable i this case. – timw4mail Nov 03 '11 at 14:46
  • Comparing the JSON strings *might* work, but there's nothing that guarantees the properties of the two objects will be serialized in the same order. (Object properties have no real "order" imposed on them by the JS specs, last i checked.) Translation: two objects with the same properties might not end up with the exact same JSON serialization. In fact, AFAIK, JS doesn't even guarantee that *the same object serialized twice* will give you two identical strings. Just so happens that most implementations are deterministic enough that people don't think about it. – cHao May 08 '12 at 20:23

1 Answers1

2

When you compare objects in JS, you are checking to see if they are the same object and not identical objects.

Converting to JSON turns an object into a string. Converting from JSON creates a new object based on the JSON data.

If you want to check if two objects are identical, then see How do you determine equality for two JavaScript objects?.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335