Understanding JSON in JavaScript
JavaScript Object Notation (JSON) is a lightweight data-interchange format for storing and exchanging data like XML. Many developers use it for configurations, APIs, and data serialization because of its simplicity. Its structure is based on key-value pairs and arrays, making it easy to parse and generate in different programming languages. Whether it is exchanging data between client and server or even storing structured information, JSON has become the standard for modern web applications.
JSON Data Types
JSON supports various data types such as strings, arrays, booleans, null, numbers, and objects — the most complex type in this category. Objects organize data in key-value pairs for a structured data representation. These types enable flexible data representation in different web applications, making it a widely used format for data exchange.
Example of JSON type representation:
// JSON type representation
{
"Sweeter": "woolen",
"isWornOut": true
}“Sweeter”: “woolen”
- The key “Sweeter” holds a string value “woolen”, indicating its type of material.
“isWornOut”: true
- The key “isWornOut” holds a boolean value true, representing whether the sweater is worn out.
This representation enables web applications to parse and manipulate data easily.
Working with Arrays and Objects
JSON structure can also be an array containing string values. Check the code below;
// Array with string values
[
"Radio",
"Watch",
"Iron Box",
"Television",
"Sound bar"
]JSON can also have objects inside the array like this;
// Objects inside the array
[
{
"name": "Ben",
"age": 32,
"isDeveloper": true,
"country": "Kenya"
},
{
"name": "Alfonse",
"age": 45,
"isProfessor": true,
"isDeveloper": false,
"country": "Nigeria"
}
]This array contains two objects, each representing a person with its attributes; the first is Ben, and the second is Alfonse.
Get Ben Willys’s stories in your inbox
Join Medium for free to get updates from this writer.
Using the previous JSON file, we also add array values inside our objects that are in the array, like this;
// Objects having array as values
[
{
"name": "Ben",
"age": 32,
"isDeveloper": true,
"country": "Kenya",
"skills": ["JavaScript", "React", "Tailwind", "Python"]
},
{
"name": "Alfonse",
"age": 45,
"isProfessor": true,
"isDeveloper": false,
"country": "Nigeria",
"skills": ["Project Management", "Lecturing", "Engineering"]
}
]- The “skills” is a key in each object that holds an array representing the person’s skillset.
Converting Data with JSON.stringify()
JSON uses the stringify method to convert JavaScript objects into valid JSON strings.
// JSON String
const names = [
"Radio",
"Watch",
"Iron Box",
"Television",
"Sound bar"
];
const jsString = JSON.stringify(names);
console.log(jsString); //Output: ["Radio","Watch","Iron Box","Television","Sound bar"]In the above code, names is a constant holding an array. The JSON.stringify() converts the array into a JSON string, and when called within the console.log method, it prints the result as a string. JSON string represents data in a structured format, either as objects or arrays.
// Converting JSON String
const persons = [
{
"name": "Ben",
"age": 32,
"isDeveloper": true,
"country": "Kenya",
"skills": ["JavaScript", "React", "Tailwind", "Python"]
},
{
"name": "Alfonse",
"age": 45,
"isProfessor": true,
"isDeveloper": false,
"country": "Nigeria",
"skills": ["Project Management", "Lecturing", "Engineering"]
}
];
const jsString = JSON.stringify(persons);
console.log(jsString); //Output (truncated): [{"name":"Ben","age":32,"isDeveloper":true,..}]In this code, the constant persons is an array containing two objects, each representing a person with its properties. The JSON.stringify() method is used to convert JavaScript objects into JSON strings. It is very useful for sending data over the network, saving it in storage, and logging it. A JSON string is a plain array that can’t be manipulated with the array methods. In many cases, developers refer to it as a string representation of an array.
Parsing Data with JSON.parse()
The JSON.parse() is used to convert JSON strings into JavaScript objects or arrays. A JavaScript array is a data structure that is used to store multiple values, allowing for direct manipulation or access using methods like push() and map(). In programming, parse means converting data from one format to another. The code below shows a JSON string being converted into a JavaScript object.
Example code
// Converting JSON String
const str = `{
"data": [
{
"ShoppingList": [
"Eggs",
"Vegetables",
{
"Fruits": [
"Apples",
"Oranges",
"Guava"
]
}
]
}
]
}`;
const jsString = JSON.parse(str);
console.log(jsString.data[0].ShoppingList); //Output: [ 'Eggs', 'Vegetables', { Fruits: [ 'Apples', 'Oranges', 'Guava' ] } ]In this code, the JSON.parse() method converts the str string into a JavaScript object. jsString has a data array containing a key called Fruits. Accessing jsString.data[0].ShoppingList retrieves the ShoppingList array, containing Eggs, Vegetables, and a Fruits object. The Fruit object contains an array of fruit names like ‘Apples’, ‘Oranges’, and ‘Guava’. This structure allows for nesting different items under one list and grouping fruits separately for better organization.
Therefore, jsString.data[0].ShoppingList is a JavaScript array, it allows for direct access and manipulation of data. We can use methods like push() and splice() to access specific items using the index notation.
Fetching JSON Data
The fetch() method uses the response.json() method to convert a JSON string from the server into a JavaScript object/array, depending on the structure of the JSON. It’s important to note that fetch returns a promise for handling asynchronous requests. In the following examples, fetchJSON.js file uses the fetch() method to retrieve data from the getJSON.php file:
getJSON.php:
<?php
echo '{
"data": [
{
"ShoppingList": [
"Eggs",
"Vegetables",
{
"Fruits": [
"Apples",
"Oranges",
"Guava"
]
}
]
}
]
}';
?>fetchJSON.js:
// fetching JSON data
fetch("http://localhost:8000/getJSON.php")
.then(response => response.json())
.then(value => console.log(value))
.catch(error => console.log(error));
// output: [ 'Eggs', 'Vegetables', { Fruits: [ 'Apples', 'Oranges', 'Guava' ] } ]In the above codes, fetch() sends a request to getJSON.php and returns a promise from the server via the URL http://localhost:8000/getJSON.php. The response.json() parses the JSON string into a JavaScript object. The console.log(value) prints the parsed object/array to the console, while the catch() handles any error that might occur over the network.
Conclusion
In conclusion, JSON is crucial in modern web development because it provides a simple and efficient way to structure, store, and exchange data between the server and a client. Its ease of use, compatibility with JavaScript, and ability to handle complex data structures make it a useful tool for developers working with APIs, servers, and other data-driven applications.









