The Wayback Machine - https://web.archive.org/web/20241006235050/https://www.geeksforgeeks.org/javascript-json/
Open In App

JavaScript JSON

Last Updated : 31 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JSON, short for JavaScript Object Notation, is a way to organize data. It’s similar to XML in that it structures information, but it’s more lightweight and easier for humans to read and write. Web applications commonly use JSON to exchange data between each other.

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. JSON is built on two structures:

  1. A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  2. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Why JSON? 

The fact that whenever we declare a variable and assign a value to it, it’s not the variable that holds the value but rather the variable just holds an address in the memory where the initialized value is stored. Further explaining, take for example:

let age=21;

when we use age, it gets replaced with 21, but that does not mean that age contains 21, rather what it means is that the variable age contains the address of the memory location where 21 is stored.

How is JSON helpful?

Well, yes, you are right! it is fine here till now but imagine you have to transfer the data and use it somewhere else (like an API maybe), so how will we share this?

One way could be to send your computer’s entire memory along with the address of the locations that are required, as you might have understood now this is not at all a good way to do it, it is risky to send your entire computer memory.

Here comes JSON to the rescue, JSON serializes the data and converts it into a human-readable and understandable format, which also makes it transferal and to be able to communicate.

Characteristics of JSON

  • Human-readable and writable: JSON is easy to read and write.
  • Lightweight text-based data interchange format: JSON is simpler to read and write when compared to XML.
  • Widely used: JSON is a common format for data storage and communication on the web.
  • Language-independent: Although derived from JavaScript, JSON can be used with many programming languages.

JSON Syntax Rules

JSON syntax is derived from JavaScript object notation syntax:

  • Data is in name/value pairs Example:
{ "name":"Thanos" }


Types of Values:

Array: An associative array of values.

Boolean: True or false.

Number: An integer.

Object: An associative array of key/value pairs.

String: Several plain text characters which usually form a word.


Data is separated by commas Example:

{ "name":"Thanos", "Occupation":"Destroying half of humanity" }
  • Curly braces hold objects Example:
let person={ "name":"Thanos", "Occupation":"Destroying half of humanity" }
  • Square brackets hold arrays Example:
let person={ "name":"Thanos", "Occupation":"Destroying half of humanity", "powers": ["Can destroy anything with snap of his fingers", "Damage resistance", "Superhuman reflexes"] }

JSON Objects

A JSON object is a collection of key/value pairs. The keys are strings, and the values can be strings, numbers, objects, arrays, true, false, or null.

JSON Arrays

A JSON array is an ordered collection of values. The values can be strings, numbers, objects, arrays, true, false, or null.


Example: This example shows the JSON text.

javascript
{
    "Avengers": [
        {
            "Name": "Tony stark",
            "also known as": "Iron man",
            "Abilities": [
                "Genius",
                "Billionaire",
                "Playboy",
                "Philanthropist"
            ]
        },
        {
            "Name": "Peter parker",
            "also known as": "Spider man",
            "Abilities": [
                "Spider web",
                "Spidy sense"
            ]
        }
    ]
}

Convert a JSON Text to a JavaScript Object

We will see how to convert a JSON text into a JavaScript Object.

Example: We will be using the JSON.parse() method to convert the JSON text to a JavaScript Object.

JavaScript
let text = '{"model":[' +
    '{"carName":"Baleno","brandName":"Maruti" },' +
    '{"carName":"Aura","brandName":"Hyndai" },' +
    '{"carName":"Nexon","brandName":"Tata" }]}';

const cars = JSON.parse(text);
console.log("The car name is: " + cars.model[2].carName + 
    " of brand: " + cars.model[2].brandName);

Output
The car name is: Nexon of brand: Tata

JSON to JavaScript Object

To convert JSON text into a JavaScript object, you can use the JSON.parse() method as shown in the example above. This method parses the JSON string and constructs the JavaScript value or object described by the string.

JavaScript JSON – FAQs

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is often used for transmitting data in web applications.

How do you create a JSON object in JavaScript?

A JSON object is created using JavaScript object notation. It is a text format that represents structured data.

How do you convert a JavaScript object to a JSON string?

You use the JSON.stringify() method to convert a JavaScript object to a JSON string.

How do you parse a JSON string to a JavaScript object?

You use the JSON.parse() method to parse a JSON string and convert it to a JavaScript object.



Previous Article
Next Article

Similar Reads

Why does Vite create multiple TypeScript config files: tsconfig.json, tsconfig.app.json and tsconfig.node.json?
In Vite TypeScript projects you may have noticed three typescript configuration files, tsconfig.json, tsconfig.app.json, and tsconfig.node.json. Each file is used for a different purpose and understanding their use cases can help you manage TypeScript configurations for your project. In this article, you will learn about the three TypeScript config
6 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
Convert JSON String to Array of JSON Objects in JavaScript
Converting a JSON string to an array of JSON objects in JavaScript involves transforming a structured text format (JSON) into a usable JavaScript array. This allows developers to work directly with the data, enabling easier manipulation, analysis, and display of information. There are two approaches to solving this problem, which are discussed belo
2 min read
JSON Modify an Array Value of a JSON Object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi
2 min read
How to transforms JSON object to pretty-printed JSON using Angular Pipe ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p
3 min read
How to Write Postman Test to Compare the Response JSON against another JSON?
In the era of API-driven development, testing the API responses to ensure their correctness is of paramount importance. One such test includes comparing the JSON response of an API against a predefined JSON. In this article, we will delve into how to write a Postman test for this purpose. Table of Content What is Postman?JSON and its Role in APIsWh
4 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more.Approach: We are going to fetch JSON data from one of free website,
2 min read
Difference between package.json and package-lock.json files
In Node, package.json file contains the list of dependencies and scripts in a project while the package.lock.json specifies their respective versions to ensure consistent installations in different environments. In this article, we will learn the major differences between package.json and package.lock.json and their needs in Node. Table of Content
4 min read
How to Convert JavaScript Class to JSON in JavaScript?
When transmitting or saving class data in a structured manner, converting an instance of a class into a JSON format is also necessary. JSON (JavaScript Object Notation) supplies a method of turning objects into strings. They can be sent across a network or stored in a database, properties of the instance of the class should be taken out and changed
2 min read
Javascript | JSON PHP
JSON stands for the JavaScript Object Notation. It is used to exchanging and storing the data from the web-server. JSON uses the object notation of JavaScript. JavaScript objects can be converted into the JSON and receive JSON format text into the JavaScript objects. Converting the JavaScript object into the JSON format is done by the given functio
7 min read
JavaScript | JSON HTML
HTML table: In the HTML, tables are defined by <table> tag, table's header are defined by <th> tag and by default table's header are placed in center and it is bold and row of the table is defined by <tr> and the data or information of the row is defined by <td> tag. Below code shows the demonstration of the HTML table: Code
3 min read
JavaScript | JSON Arrays
The JSON Arrays is similar to JavaScript Arrays. Syntax of Arrays in JSON Objects: // JSON Arrays Syntax { "name":"Peter parker", "heroName": "Spiderman", "friends" : ["Deadpool", "Hulk", "Wolverine"] } Accessing Array Values: The Array values can be accessed using the index of each element in an Array. C/C++ Code <!DOCTYPE html> <html>
2 min read
JavaScript JSON parse() Method
The JSON.parse() method in JavaScript is used to parse a JSON string which is written in a JSON format and returns a JavaScript object. Syntax: JSON.parse( string, function ) Parameters: This method accepts two parameters as mentioned above and described below: string: It is a required parameter and it contains a string that is written in JSON form
2 min read
JavaScript | Remove a JSON attribute
In this article, we will see how to remove a JSON attribute from the JSON object. To do this, there are few of the mostly used techniques discussed. First delete property needs to be discussed. Delete property to Remove a JSON Attribute This keyword deletes a property from an object: This keyword deletes both the value of the property and the prope
2 min read
JavaScript | Convert an array to JSON
Here is a need to convert an array into a JSON_Object. To do so we are going to use a few of the most preferred techniques. First, we need to know a few methods. 1) Object.assign() method This method copies the values of all properties owned by enumerables from source objects(one or more) to a target object. Syntax: Object.assign(target, ...sources
2 min read
JavaScript | Add new attribute to JSON object
The task is to add a JSON attribute to the JSON object. To do so, Here are a few of the most used techniques discussed.Example 1: This example adds a prop_11 attribute to the myObj object via var key. C/C++ Code <!DOCTYPE HTML> <html> <head> <title> JavaScript | Add new attribute to JSON object. </title> </head>
2 min read
How to send a JSON object to a server using Javascript?
JavaScript Object Notation (JSON). It is a lightweight data transferring format. It is very easy to understand by human as well as machine. It is commonly used to send data from or to server. Nowadays it is widely used in API integration because of its advantages and simplicity.In this example we are going to use AJAX (Asynchronous JavaScript And X
2 min read
How to swap key and value of JSON element using JavaScript ?
In this article, we will swap the key and value of JSON elements using JavaScript. Given a JSON object and the task is to swap the JSON object key with values and vice-versa with the help of JavaScript. Below are the following approaches: Using for loopUsing Object.keys() and ForEach() MethodUsing Object.entries() and map() MethodApproach 1: Using
2 min read
How to convert JSON results into a date using JavaScript ?
The task is to convert a JSON result to JavaScript Date with the help of JavaScript. There are two methods which are discussed below: Approach 1: Use substr() method to get the integer part of the string.Use the parseInt() method followed by Date() to get the JavaScript date. Example: This example implements the above approach. C/C++ Code <h1 st
2 min read
JavaScript SyntaxError - JSON.parse: bad parsing
This JavaScript exception thrown by JSON.parse() occurs if string passed as a parameter to the method is invalid. Message: SyntaxError: JSON.parse: unterminated string literal SyntaxError: JSON.parse: bad control character in string literal SyntaxError: JSON.parse: bad character in string literal SyntaxError: JSON.parse: bad Unicode escape SyntaxEr
2 min read
How to filter nested JSON object to return certain value using JavaScript ?
Given a collection that contains the detail information of employees who are working in the organization. We need to find some values from that nested collections of details. That collection is known as the JSON object and the information inside object are known as nested JSON object. Example 1: We create the nested JSON objects using JavaScript co
4 min read
How to print a circular structure in a JSON like format using JavaScript ?
The circular structure is when you try to reference an object which directly or indirectly references itself. Example: A -> B -> A OR A -> A Circular structures are pretty common while developing an application. For Example, suppose you are developing a social media application where each user may have one or more images. Each image may be
4 min read
JavaScript JSON Complete Reference
JSON or JavaScript Object Notation is a format for structuring data. Like XML, it is one of the ways of formatting the data, such format of data is used by web applications to communicate with each other. Syntax: JSON function() Example: The example of the JSON parse() Method. C/C++ Code let obj = JSON.parse('{"var1":"Geeks",
1 min read
How to Convert CSV to JSON file and vice-versa in JavaScript ?
CSV files are a common file format used to store data in a table-like manner. They can be particularly useful when a user intends to download structured information in a way that they can easily open and read on their local machine. CSV files are ideal for this because of their portability and universality. In this article, we will explain how to c
3 min read
JSON vs JavaScript Object
In this article, we will learn about JSON and JavaScript Object and the key differences between them. What is JavaScript Object? The foundation of contemporary JavaScript is made up of objects, which are the most significant data type in JavaScript. The primitive data types in JavaScript (Number, String, Boolean, null, undefined, and symbol) are si
3 min read
How to transform JSON text to a JavaScript object ?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. As its name suggests, JSON is derived from the JavaScript programming language, but it’s available for use by many languages including Python, Ruby, PHP, and Java, and hence, it can be said as language-independent. For humans, it is easy to read and write and for machines,
3 min read
Create a chart from JSON data using Fetch GET request (Fetch API) in JavaScript
In this article, we are going to create a simple chart by fetching JSON Data using Fetch() method of Fetch API. The Fetch API allows us to conduct HTTP requests in a simpler way. The fetch() method: The fetch method fetches a resource thereby returning a promise which is fulfilled once the response is available. Syntax: const response = fetch(resou
3 min read
Javascript - Catching error if json key does not exist
In this article, we will discuss the error handling when a key is not present inside the javascript object. A JSON is a string format that encloses a javascript object in double-quotes. Example: '{"site": "gfg"}' A JSON object literal is the javascript object present inside the JSON String. Example: {"site": "gfg"} The key/value pairs are present i
2 min read
How to traverse between children in JavaScript to create breadcrumb UI from JSON ?
Traversing between children in JavaScript to create breadcrumb UI from JSON can be done in several ways, but one of the most efficient ways is to use recursion. A breadcrumb is a type of navigation that shows the user's current location within a website or application. It is usually displayed as a series of links separated by a delimiter, such as "
4 min read