JavaScript and JSON
the preferred data format of the internet
JSON (JavaScript Object Notation) allows for storing small sets of data in a relatively simple but robust structure:
The basic structure of a JSON object
The simplest JSON object looks like:
In a browser console, let us take the basic JSON object above into JavaScript and assign it a variable called jsonObject:
Notations for the notations
We could then use the dot notation object.property in the console:
Or, we could use the bracket notation object["property"]:
The bracket notation becomes useful when the property names lengthen, so much that we would need to use "kebab-notation", the stringing of multiple words with dashes!
We would then access that property like such:
Objects with more than one property
Naturally, an object could have multiple property-value pairs:
Calling the above jsonObject, we would enter jsonObject.property2 or jsonObject["property2"] into a console to yield "value2"
Objects inside of objects
The object could also have properties with values that themselves have sub-objects:
Calling the above jsonObject, we could enter one of the following:
jsonObject.property2.property2B
jsonObject["property2"]["property2B"]
We can then infer here that this versatile structure could allow for quite complex objects with many properties and sub-properties to the desired degree!
JSON.parse()
JSON.parse()
Converts a JSON string into a JavaScript object:
When passed into JSON.parse
:
The parsedObject
variable will become this:
JSON.stringify()
JSON.stringify()
Converts a JavaScript object into a JSON string so that this:
passed into the JSON.stringify
:
becomes this JSON string:
Last updated