1. javascript
  2. /basics
  3. /json

JSON (JavaScript Object Notation)

Definition

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:

  • Keys and values are separated by a colon (:).
  • Key-value pairs are separated by commas (,).
  • Arrays are enclosed in square brackets ([ and ]).
  • Objects are enclosed in curly braces ({ and }).
  • Strings are enclosed in double quotes (").
  • Numbers and booleans are not enclosed in quotes.

Example Syntax

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); // Outputs "John Doe"

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 Types

In JSON, there are six data types that can be used:

  • Number: a signed decimal number that may contain a fractional part and may use exponential E notation, but cannot include non-numbers such as NaN.
  • String: a sequence of zero or more Unicode characters. Strings are delimited with double-quotation marks and support a backslash escaping syntax.
  • Boolean: represents one of two values: true or false.
  • Array: an ordered list of zero or more values, each of which may be of any type. Arrays are delimited with square brackets and use commas to separate items.
  • Object: an unordered collection of name-value pairs, where the name is a string and the value can be of any type. Objects are delimited with curly braces and use commas to separate name-value pairs.
  • null: represents the absence of a value or a null value.

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:

  • Proper formatting of your JSON data makes it easier to read and understand. Use indentation and newlines to improve readability.
  • Use keys that are descriptive and meaningful. Avoid using abbreviations or short forms that may not be easily understood by others.
  • When naming keys, use camelCase instead of snake_case or kebab-case. This is the standard in JavaScript and is more readable.
  • When defining strings, use double quotes rather than single quotes. This is the standard in JSON and ensures compatibility with some older browser versions.
  • Use null to represent empty or non-existent values, rather than using an empty string or other placeholder value.
  • Before working with JSON data, it is important to validate it to ensure that it is properly formatted and does not contain any errors. You can use a JSON lint tool to validate your data.
  • Choose the appropriate data type for your values. For example, use numbers for numeric values and booleans for true/false values.
  • Be consistent in your use of keys and data types. This makes your data easier to work with and reduces the risk of errors.

Further Learning

Frequently Asked Questions about JSON

1. How do I parse a JSON string into a JavaScript object?

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); // Output: "John"

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); 
// Output: '{"name":"John","age":30,"city":"New York"}'

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); // Output: "John"

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"]); // Output: "John"

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]]); // Output: "John"

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:

// dot notation
let jsObject = {name: "John", age: 30, city: "New York"};
jsObject.gender = "male"; 
console.log(jsObject); // Output: {name: "John", age: 30, city: "New York", gender: "male"}

// bracket notation
let jsObject = {name: "John", age: 30, city: "New York"};
jsObject["address"] = "New York"; 
console.log(jsObject); // Output: {name: "John", age: 30, city: "New York", address: "New York"}

2 - To remove a key-value pair, you can use the delete operator:

// dot notation
let jsObject = {name: "John", age: 30, city: "New York"};
delete jsObject.age; 
console.log(jsObject); // Output: {name: "John", city: "New York"}

// bracket notation
let jsObject = {name: "John", age: 30, city: "New York"};
delete jsObject["city"]; 
console.log(jsObject); // Output: {name: "John", age: 30}

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); // Output: {name: "John", age: 30, city: "New York", gender: "male", address: "New York"}

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); // Output: {name: "John", age: 30, city: "New York", gender: "male", address: "New York"}

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 Web

JSON Lint - The best JSON Validator tool

How to parse JSON

MDN - Working with JSON data