A Comprehensive Guide To Working With JSON in JavaScript
This tutorial covers everything you need to know about working with JSON objects in JavaScript. It includes topics such as creating, parsing, and manipulating JSON data.
Join the DZone community and get the full member experience.
Join For FreeWhat Is a JSON Object?
JSON stands for Javascript Object Notation and is a standard text-based format for representing structured data based on JavaScript object syntax. JSON defines only two data structures: objects and arrays. JSON object is a data type that consists of key/value pairs surrounded by curly braces. JSON array is a list of values. JSON objects are often used when data is sent from a server to a webpage or when data is stored in files or databases. JSON closely resembles Javascript object literal syntax but can be used independently from Javascript. Many programming environments support reading and generating JSON.
Features of JSON Objects
- They are written in key/value pairs, separated by commas. A key is a string enclosed in double quotes, and a value must be a JSON data type as below
- string
- number
- object
- array
- boolean
- null
- They are surrounded by curly braces {}. Curly braces can also be used to nest objects within objects, creating a hierarchical structure.
- Arrays are enclosed in brackets [], and their values are separated by a comma (,). Each value in an array may be of a different type, including another array or an object.
- They are case-sensitive, meaning the keys and values must match exactly in spelling and capitalization.
- They don’t allow trailing commas. In simple terms, there should not be any text outside the curly braces or inside the double quotes that are not part of the key/value pairs.
- They don’t allow comments.
JSON offers several benefits, making it a popular choice for representing structured data:
- Simplicity and readability: JSON is straightforward and easy to understand. Unlike more verbose formats like XML, JSON is relatively easy to read as-is. Its concise syntax allows for efficient data representation.
- Ease of parsing: JSON is simpler and faster to parse than XML.
- Flexibility: JSON supports various data types and object hierarchies, and relationships can be preserved during transmission and reassembled appropriately at the receiving end.
- Widespread usage: Most modern APIs accept JSON requests and issue JSON responses, making it universal for data exchange between systems
Examples of JSON Objects
Basic JSON object: |
Nested JSON object: It is a data type that consists of a list of name/value pairs, where one or more of the values are another JSON object.
|
Array of JSON object: |
Parsing JSON Objects
Parsing is the method of converting a JSON object into a native Javascript object.
JSON.parse()
method: The JSON.parse()
method parses a string and returns a Javascript object. The string has to be in JSON format.
Syntax: JSON.parse(string, function)
Parameter |
Required/Optional |
Description |
String |
Required |
A string written in JSON format |
Reviver function |
Optional |
A function that takes a key and a value as parameters and returns a modified value or undefined to delete the property. The function is called for each item. Any nested objects are transformed before the parent. |
Example
var text = '{"name": "Natalie", "married": false, "age": 21, "city": "New York", "zip" : "10001", "awards": null}';
var obj = JSON.parse(text, function (key, value) {
if (key === "name") {
return value.toUpperCase();
} else {
return value;
}
});
console.log(obj);
Output
{
name: 'NATALIE',
married: false,
age: 21,
city: 'New York',
zip: '10001',
awards: null
}
JSON.stringify()
Method
This method converts Javascript objects into strings. When sending data to a web server the data has to be a string. JSON.stringify()
also works with arrays.
Syntax: JSON.stringify(obj, replacer, space)
Parameter |
Required/Optional |
Description |
Obj |
Required |
The value to convert to a string |
Replacer |
Optional |
A function or an array used to transform the result. The replacer is called for each item. |
Space |
Optional |
A string to be used as white space (max 10 characters), or a number, from 0 to 10, to indicate how many space characters to use as white space. |
Example
var obj = {"name": "Natalie", "married": false, "age": 21, "city": "New York", "zip" : "10001", "awards": null};
var text = JSON.stringify(obj, function (key, value) {
if (key === "name") {
return value.toUpperCase();
} else {
return value;
}
});
console.log(text);
Output
{"name":"NATALIE","married":false,"age":21,"city":"New York","zip":"10001","awards":null}
/*Insert the word SPACE for each white space:*/
var newText = JSON.stringify(obj, null, "space");
console.log(“Text with the word space “+ newText);
Output
Text with the word space {
space"name": "Natalie",
space"married": false,
space"age": 21,
space"city": "New York",
space"zip": "10001",
space"awards": null
}
Navigation of JSON Objects
The dot (.)
or bracket ([])
notation can be used to navigate into its properties and access their values.
// Access the name using dot notation
var obj = {"name": "Natalie", "married": false, "age": 21, "city": "New York", "zip" : "10001", "awards": null};
console.log(obj.name); Output: Natalie
// Access the city using dot notation
console.log(obj["city"]; Output: New York
var obj_array = [ { "name": "Natalie", "age": 21 }, { "name": "David", "age": 37 }, { "name": "Mark", "age": 43 } ]
// Access the first member's name using dot and bracket notation
console.log(obj_array[0].name); Output: Natalie
// Access the second member's age using dot and bracket notation
console.log(obj_array[1][ "age"]); Output: 37
Object.keys()
Method
keys()
method returns an array of a given object’s own enumerable string-keyed property names. The keys()
method, being a static method, is called using the Object class name.
Syntax: Object.keys(obj)
Parameter |
Required/Optional |
Description |
obj |
Required |
The object whose enumerable properties are to be returned |
Object.values()
Method
values()
method returns an array of a given object’s own enumerable string-keyed property values. The values()
method, being a static method, is called using the Object class name.
Syntax: Object.values(obj)
Parameter |
Required/Optional |
Description |
obj |
Required |
The object whose enumerable properties are to be returned |
Object.entries()
Method
This method returns an array of key-value pairs of an object’s enumerable properties. The entries()
method, being a static method, is called using the Object class name.
Syntax: Object.entries(obj)
Parameter |
Required/Optional |
Description |
obj |
Required |
The object whose enumerable properties are to be returned |
Example
var obj = {"name": "Natalie", "married": false, "age": 21, "city": "New York", "zip" : "10001", "awards": null};
var keys = Object.keys(obj);
var values = Object.values(obj);
var entries = Object.entries(obj);
console.log("Array of keys :");
console.log(keys);
console.log("Array of values :");
console.log(values);
console.log("Array of entries :");
console.log(entries);
Output
Array of keys :
[ 'name', 'married', 'age', 'city', 'zip', 'awards' ]
Array of values :
[ 'Natalie', false, 21, 'New York', '10001', null ]
Array of entries :
[
[ 'name', 'Natalie' ],
[ 'married', false ],
[ 'age', 21 ],
[ 'city', 'New York' ],
[ 'zip', '10001' ],
[ 'awards', null ]
]
for loop
A for loop repeats until a specified condition is evaluated to be false.
Syntax: for (initialization; condition; expression) {code block to be executed}
Parameter |
Required/Optional |
Description |
Initialization
|
Required |
Executed one time before the execution of the code block |
Condition |
Required |
The condition for executing the code block |
Expression |
Required |
Executed every time after the code block has been executed |
Example
var obj = [ { "name": "Natalie", "age": 21, "married": true }, { "name": "David", "age": 37, "married": false }, { "name": "Mark", "age": 43, "married": true } ];
for(var i=0; i<obj.length; i++) {
console.log("Name: " + obj[i]["name"]); //using bracket notation
console.log("Married Status: " + obj[i].married); //using dot notation
}
Output
Output
Name: Natalie
Married Status: true
Name: David
Married Status: false
Name: Mark
Married Status: true
for…in
Loop
The for...in
statement iterates over all enumerable string non-symbol properties of an object including inherited enumerable properties. The code block inside the loop is executed once for each property.
Syntax: for (item in object) {code block to be executed}
Parameter |
Required/Optional |
Description |
item |
Required |
A variable to iterate over the properties. |
object |
Required |
The object to be iterated. |
Example
var obj = [ { "name": "Natalie", "age": 21, "married": true }, { "name": "David", "age": 37, "married": false }, { "name": "Mark", "age": 43, "married": true } ];
for(item in obj) {
console.log("Name: " + obj[item]["name"]); //using bracket notation
console.log("Married Status: " + obj[item].married); //using dot notation
}
Output
Name: Natalie
Married Status: true
Name: David
Married Status: false
Name: Mark
Married Status: true
for…of
Loop
A for..of
loop operates on the values sourced from an iterable object one by one in sequential order.
Syntax: array.forEach(variable of iterable object) {statement}
Parameter |
Required/Optional |
Description |
Variable |
Required |
For every iteration, the value of the next property is assigned to the variable. A variable can be declared with const, let, or var. |
Iterable object |
Required |
The source of values on which the loop operates. |
Example
var obj = [ { "name": "Natalie", "age": 21, "married": true }, { "name": "David", "age": 37, "married": false }, { "name": "Mark", "age": 43, "married": true } ];
for(var item of obj) {
console.log("Name: " + item["name"]); //using bracket notation
console.log("Married Status: " + item.married); //using dot notation
}
Output
Name: Natalie
Married Status: true
Name: David
Married Status: false
Name: Mark
Married Status: true
forEach()
Method
The forEach()
method calls a function for each element in an array. It must take at least one parameter which represents the elements of an array.
Syntax: array.forEach(function(currentValue, index, array), thisValue)
Parameter |
Required/Optional |
Description |
Function |
Required |
A function to run for each element of the array |
currentvalue |
Required |
The value of the current element |
index |
Optional |
Index of the current element |
Array |
Optional |
Array of the current element |
Thisvalue |
Optional |
A value passed to the function as this value. Default undefined. |
Example
var obj = [ { "name": "Natalie", "age": 21, "married": true }, { "name": "David", "age": 37, "married": false }, { "name": "Mark", "age": 43, "married": true } ];
obj.forEach((item, index, arr) => {
console.log("Details of element: " +index);
console.log("Name: "+arr[index]["name"]);
console.log("Age: "+item.age);
});
Output
Details of element: 0
Name: Natalie
Age: 21
Details of element: 1
Name: David
Age: 37
Details of element: 2
Name: Mark
Age: 43
Conclusion
JSON is commonly employed for transmitting data between servers and web applications. The JSON’s flexibility, ease of parsing, and simplicity allow software developers to work with structured data efficiently in various programming environments.
Opinions expressed by DZone contributors are their own.
Comments