1.1 JSON

JSON, or JavaScript Object Notation, is a fairly simple tool for formatting and transmitting data. It is often used for sending data between APIs and computer systems. Despite having a syntax derived from Javascript, JSON can be used in many languages from Python, Java, C++, C, and many more; it is language independent. JSON is stored as plain text (not belonging to any language) and has low file sizes. All of the above makes JSON easy to transfer and work with.

How JSON Works:

  1. Data comes in name:value pairs. This should be a familiar format for those familiar with coding as an object (as in the case of JSON), dictionary, hash table, etc
  2. Multiple pairs may create an ordered list (a JSON array). This is a widely known format as well, called an array, list, vector, etc.

For example, using JSON to create the object “cats”:

'{
"Cats":[
{"cat_name": "Persian"}
{"cat_name": "Sphynx"}
{"cat_name": "Siamese"}
]
}'

Each unordered set of name:value pairs is considered an object and enclosed in curly brackets. They are separated by commas. The full list of values is considered an array and enclosed by square brackets. A value in the name:value pair can be a string, number (including scientific notation), boolean, array, object (most common) or even null!

For example, adding onto the example above:

‘{
“Cats”: [
{“cat_name”: “Persian”, “cat_rank”:2}
{“cat_name”: “Sphynx”, “cat_rank”:1}
{“cat_name”: “Siamese”, “cat_rank”:3}
{“cat_name”: “Munchkin”, “cat_rank”: Null}
]
}’

We don’t have to only write arrays in JSON. We can also write strings of objects:

'{"cat_name": "Persian"}'

While data can be extracted from a JSON string (with JSONata), it’s most commonly converted into Javascript to be read. Due to how similar the syntax of JSON and Javascript are, Javascript contains functions designed to convert strings and arrays of JSON into Javascript objects and arrays and back again. This is called deserialization:

JSON.parse(JSON string)

Converting code into JSON text is called serialization. To convert Javascript objects into JSON strings we use:

JSON.stringify(code object)

For example, to convert our JSON array into a Javascript array we can do:

const Cats = '{"Cats": [{"cat_name": "Persian", "cat_rank":2} {"cat_name": "Sphynx", "cat_rank":1} {"cat_name": "Siamese", "cat_rank":3}'
const cats_js = JSON.parse(Cats)
console.log(Cats.cat_name)

And to convert the Javascript array back into a JSON array we can do: