Sebi Sebi - 1 year ago 59
JSON Question

Comparing "key" values in javascript tuples

I'm using associative array to create json objects, serialize and send them to a third party:

var MSG = {}
MSG["SESSION_START"] = 0x0000;
MSG["DONE"] = 0x0001;

var session_id = gen_rand_no();
var msg_tuple = {MSG["SESSION_START"] : session_id};
var json_msg_tuple = JSON.stringify(msg_tuple);


The party would normally reply with an acknowledgement message in a form of a serialized JSON object:

var serialized_json = recv();
var json_obj = JSON.parse(serialized_json);

How can I check if the first element in the JSON object is corresponding to the MSG["DONE"] value?

In the answer of this question, it is assumed that the JSON object has a given set of attributes until the nested ones are iterated over.

Answer Source

Objects in JavaScript have no "key order" so there is no such thing as a "first element".

With that in mind, the following two options exist for testing if the key exists:

if( MSG['DONE'] in json_obj)
// or...
if( json_obj.hasOwnProperty(MSG['DONE']))