JSON vs data structure

When you see var j = {"x": 1} in JavaScript, it is plainly wrong to say that j is now JSON or references JSON or holds JSON for that matter.

binary-797263_640

That’s because j now references a data structure in memory. A data structure is not JSON nor YAML nor any other serialization format.

A data structure can sometimes be serialized to JSON or to YAML or to other formats. A data structure can sometimes be deserialized from these formats.

The code on the right side of the assignment looks like JSON. Don’t let this confuse you. It’s a JavaScript code and it evaluates to a data structure as many other JavaScript expressions do. It could easily be var j = {'a': 1, 'f': function() {} } . You wouldn’t say it’s JSON, right? There is not much difference between the two JavaScript expressions var j = {"x": 1} and var j = {'a': 1, 'f': function() {} } for this matter.

Data structure vs its serialized form

Data structure is the layout of the data. In our case it is in memory. Data structures can also be on disk, think data file of a database. Data structures are “good for” accessing and modifying the data that they hold. In our case it means one can use the expression j.x to access the field x or j.x = 7 to modify it.

Serialized form of a data is a string of characters that can be saved to a file, read from such file or sent over the network. There is no easy way to manipulate such data directly. Modifying serialized data usually involves deserializing it, modifying and serializing back.

Serialization limitations

Not any data structure can be serialized at all. Example (specific to JSON format):

var j = {}
j['circ'] = j
JSON.stringify(j)
TypeError: Converting circular structure to JSON

Not any data structure can be serialized in a way that would ensure that deserialization would produce similar data structure. Example (specific to JavaScript + JSON):

var j = {'a': 1, 'f': function() {} }
JSON.stringify(j)
'{"a":1}'

Have a nice week!

Leave a comment