JSON is a lightweight, human-readable format for storing and exchanging data. It is often used as an alternative to XML for transmitting data over the internet, as it is easier to read and write for both humans and computers. JSON is based on a subset of the JavaScript programming language, and uses a combination of dictionaries and lists to represent data.
A JSON document is a string of text that represents a collection of data. The data can be a single value, such as a number or a string, or a complex combination of values, such as an array or an object. JSON uses a few simple rules to represent these data structures:
Here is an example of a JSON document that represents a simple object with three key-value pairs:
{
"name": "John Doe",
"age": 35,
"employed": true
}
The result contains an object with three key-value pairs: "name" is a string with the value "John Doe", "age" is a number with the value 35, and "employed" is a boolean with the value true.
To parse a JSON document in a programming language, you can use a JSON library or module that provides functions for converting JSON strings into data structures that are easier to work with in your code. For example, in JavaScript, you can use the built-in JSON.parse()
function to convert a JSON string into a JavaScript object:
var jsonString = '{"name": "John Doe", "age": 35, "employed": true}';
var data = JSON.parse(jsonString);
console.log(data.name);
JSON also supports nested data structures, such as objects within objects or arrays within arrays. Here is an example of a more complex JSON document that uses nested objects and arrays:
{
"name": "John Doe",
"age": 35,
"employed": true,
"address": {
"street": "1 Main Street",
"city": "New York",
"zipcode": "10001"
},
"skills": ["JavaScript", "HTML", "CSS"]
}
The "address" key in the demo above contains an object with three key-value pairs and the "skills" key contains an array of strings.
Data TypesIn JSON, there are six data types that can be used:
Here's a demo of all data types in use:
{
"name": "John Smith",
"age": 30,
"isEmployed": true,
"skills": ["JavaScript", "Python", "HTML", "CSS"],
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zipCode": 10001
},
"phoneNumbers": [
{
"type": "mobile",
"number": "555-555-5555"
},
{
"type": "home",
"number": "444-444-4444"
}
],
"email": null
}
Best Practices
A few best practices to consider when working with JSON:
This is pretty simple, use JSON.parse() to parse a JSON string into a JavaScript object. This method takes a single argument, which is the JSON string to be parsed, and returns the corresponding JavaScript object.
let jsonString = '{"name":"John", "age":30, "city":"New York"}';
let jsObject = JSON.parse(jsonString);
console.log(jsObject.name);
However, you may want to wrap that in a try/catch in case the JSON string isn't valid, like so:
try {
let jsonString = '{name:"John", "age":30, "city":"New York"}';
let jsObject = JSON.parse(jsonString);
} catch (error) {
console.log(error);
}
2. How do I convert a JavaScript object into a JSON string?
JSON.stringify()
will do the trick here. It will convert a JavaScript object into a JSON string. This method takes a single argument, which is the JavaScript object to be converted, and returns the corresponding JSON string.
let jsObject = {name: "John", age: 30, city: "New York"};
let jsonString = JSON.stringify(jsObject);
console.log(jsonString);
The JSON.stringify()
method also accepts two additional arguments which are super handy:
1 - A replacer function that can be used to filter-out values, to transform the values, or to add values.
2 - The number of spaces to use for indentation when pretty-printing the JSON.
let jsObject = {name: "John", age: 30, city: "New York"};
let jsonString = JSON.stringify(jsObject, null, 2);
console.log(jsonString);
This will output:
{
"name": "John",
"age": 30,
"city": "New York"
}
3. How do I access a specific value within a JSON object?
There are more than a few ways to do this:
1 - Dot notation to access the value of a property by its name:
let jsObject = {name: "John", age: 30, city: "New York"};
console.log(jsObject.name);
2 - Bracket notation to access the value of a property by its name:
let jsObject = {name: "John", age: 30, city: "New York"};
console.log(jsObject["name"]);
3 - A for-in loop to access the properties and values of a JSON object:
let jsObject = {name: "John", age: 30, city: "New York"};
for (let key in jsObject) {
if (jsObject.hasOwnProperty(key)) {
console.log(key + " -> " + jsObject[key]);
}
}
4 - The Object.entries() method to get an array of key-value pairs of an object and then you can use a for-of loop to access them:
let jsObject = {name: "John", age: 30, city: "New York"};
for (let [key, value] of Object.entries(jsObject)) {
console.log(key + " -> " + value);
}
5 - If you know the key name of the property you want to access, you can use the Object.keys()
method to get an array of the keys of an object and then you can use the array index to access the specific key:
let jsObject = {name: "John", age: 30, city: "New York"};
let keys = Object.keys(jsObject);
console.log(jsObject[keys[0]]);
If the object does not have the property you're trying to access, it will return undefined instead of an error.
4. How do I add or remove key-value pairs from a JSON object?1 - To add a new key-value pair, you can use the dot notation or the bracket notation and assign a value to it:
let jsObject = {name: "John", age: 30, city: "New York"};
jsObject.gender = "male";
console.log(jsObject);
let jsObject = {name: "John", age: 30, city: "New York"};
jsObject["address"] = "New York";
console.log(jsObject);
2 - To remove a key-value pair, you can use the delete operator:
let jsObject = {name: "John", age: 30, city: "New York"};
delete jsObject.age;
console.log(jsObject);
let jsObject = {name: "John", age: 30, city: "New York"};
delete jsObject["city"];
console.log(jsObject);
If you try to delete a property that does not exist in the object, the delete operator will have no effect. Also when you delete a property, it will not only remove the key-value pair but also the key, so it will return undefined if you try to access it again.
You can also use Object.assign() method to merge two or more objects together:
let jsObject = {name: "John", age: 30, city: "New York"};
let newObject = {gender: "male", address: "New York"}
Object.assign(jsObject, newObject);
console.log(jsObject);
Or, use the spread operator (...) to merge two objects together:
let jsObject = {name: "John", age: 30, city: "New York"};
let newObject = {gender: "male", address: "New York"}
let finalObject = {...jsObject, ...newObject};
console.log(finalObject);
Pretty neat, huh? Keep in mind that if an object has a property with the same key as the object being merged, the value will be overwritten.
5. How do I loop through all the key-value pairs in a JSON object?1 - Use a for...in loop. This type of loop iterates over the properties of an object, and you can use the Object.hasOwnProperty() method to check if the property belongs to the object.
let jsObject = {name: "John", age: 30, city: "New York"};
for (let key in jsObject) {
if (jsObject.hasOwnProperty(key)) {
console.log(key + " -> " + jsObject[key]);
}
}
2 - Use the Object.keys() method along with a for...of loop. The Object.keys() method returns an array of the object's own enumerable property names.
let jsObject = {name: "John", age: 30, city: "New York"};
let keys = Object.keys(jsObject);
for (let key of keys) {
console.log(key + " -> " + jsObject[key]);
}
3 - You can also use the Object.entries() method along with a for...of loop. The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop.
let jsObject = {name: "John", age: 30, city: "New York"};
for (let [key, value] of Object.entries(jsObject)) {
console.log(key + " -> " + value);
}
4 - Use the forEach() method of the Object.keys() method to loop through the keys of the object.
let jsObject = {name: "John", age: 30, city: "New York"};
Object.keys(jsObject).forEach(function(key) {
console.log(key + " -> " + jsObject[key]);
});
5 - Use the forEach() method of the Object.entries() method to loop through the key-value pairs of the object.
let jsObject = {name: "John", age: 30, city: "New York"};
Object.entries(jsObject).forEach(([key, value]) => {
console.log(key + " -> " + value);
});
The order of the elements in the JSON object may not be preserved while looping through the key-value pairs in some engines such as javascript, it's always good to use Object.entries() or Object.keys() to loop through the key-value pairs in a JSON object.
Additional Resources Around The WebJSON Lint - The best JSON Validator tool
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.3