JSON in JavaScript
JSON is JavaScript Object Notation. It is commonly used for web storage and communication. Despite being based on JavaScript objects, JSON is a data only format and specification that is independent of language, and libraries for other computer languages are available.
The way that arrays and objects are written in JavaScript using key value pairs is similar to how JSON looks. It does have several limitations, though:
- Double quotes must be used for all property names.
- Values may be arrays, other objects, or primitives (strings, numbers, boolean values true/false, null).
- Double quotes must be used to surround string values. Backticks and single quotations are prohibited.
- Square brackets ([]) are used to indicate lists of values (arrays).
- Curly brackets ({}) are used to indicate objects.
- JSON does not support comments.
- Function calls, bindings, and other computation intensive operations are not permitted; only basic data expressions are.
An example of JSON data describing a person is:
{
“name” : “Malika”,
“age” : 50,
“profession” : “programmer”,
“languages” : [“JavaScript”, “C#”, “Python”],
“address” : {
“street” : “Some street”,
“number” : 123,
“zipcode” : “3850AA”,
“city” : “Utrecht”,
“country” : “The Netherlands”
}
}
An array with a list of languages and an additional object for the address are among the key value pairs in this object.
One standard for interacting with APIs is JSON. APIs can receive and nearly always return data in JSON format. JSON is provided to a website from database data. Data sent and received in the background without refreshing the page is usually sent and received in JSON format in AJAX applications.
JSON is a string in JavaScript, not an object. Fetch data from an API or local file is always string, even if it’s JSON. Thus, this data must be translated in order to be used as a JavaScript object or array.
Parsing JSON (JSON.parse)
JSON strings are parsed into JavaScript objects or values. JSON.parse() does this in JavaScript.
Using JSON.parse(s), the JSON string is parsed. The function returns the string’s JavaScript object, array, or primitive.
Here is an example of parsing a simple JSON string:
let str = “{\”name\”: \”Maaike\”, \”age\”: 30}”;
let obj = JSON.parse(str);
console.log(obj.name, “is”, obj.age);
Parsed obj can be used as a JavaScript object with dot or bracket notation to access its properties. The console displays “Maaike is 30”.
The reviver function is an optional second argument that JSON.parse() can accept. Before the parsed values are returned, they can be filtered or changed using this function. Converting date strings back into JavaScript Date objects is one use for it.
Serializing JSON (JSON.stringify)
Serialization converts JavaScript objects and values into JSON strings. Data saved to a file, stored locally, or transmitted over a network requires this. For this, JavaScript’s JSON.stringify() function is available.
JSON.stringify(o) is the fundamental syntax, where o is the JavaScript value (object, array, or primitive) that has to be transformed. A string that has been encoded in JSON is the return value.
Here is an example of serializing a JavaScript object:
let personObject = { // This is a JavaScript object
“name”: “Malika”,
“age”: 50,
“profession”: “programmer”,
“languages”: [“JavaScript”, “C#”, “Python”],
“address”: {
“street”: “Some street”,
“number”: 123,
“zipcode”: “3850AA”,
“city”: “Utrecht”,
“country”: “The Netherlands”
}
};
let jsonString = JSON.stringify(personObject); // Serialize the object
console.log(typeof jsonString); // Output the type
console.log(jsonString); // Output the resulting JSON string
This bit of code first logs “string” before sending {“name”: “wiesje”,”breed”: “dachshund”} to the terminal. A string is the resultant value, strdog.
The second and third parameters are optional for JSON.stringify(). The second parameter, a replacer, can be a function to change or filter data, or it can be an array of property names to include. In order to make the output string more understandable by humans, it is formatted with indentation using the third argument, space. The string is machine readable yet difficult for humans to read if it is left out.
When a JavaScript object has a toJSON() method, JSON.stringify() automatically invokes it and serializes the return result rather than the original object. For instance, the built in toJSON() method of Date objects transforms the date into a string in ISO 8601 format for serialization.
Unsupported Types and Limitations
All JavaScript values cannot be represented using JSON syntax, which is a subset of JavaScript syntax. The following JavaScript values and types are not supported:
- NaN, Infinity, Infinity are serialized to null.
- Function properties (methods) are skipped.
- undefined values are skipped. If a property value cannot be serialized, that property is omitted.
- Symbol keys and values are skipped.
- RegExp and Error objects are not supported and cannot be serialized or restored directly.
- Objects with cyclic self references (where objects directly or indirectly reference each other in a loop) will cause an error during serialization.
Take notice of these limitations, particularly with regard to Dates (which are serialized to strings but not restored to Date objects by default by JSON.parse()) and types like RegExp and Function, even if JSON.stringify() and JSON.parse() can be used combined to build a deep duplicate of a serializable object.