Data Conversion: From JavaScript Objects To JSON

Photo of author

The full form of JSON is JavaScript Object Notation. JSON language is easy to read and understand by machines and humans. It is a data exchange format that is easy to generate and parse. It transfers data between the website and the server. This article will guide you on how to convert JavaScript objects to JSON.

JSON

JavaScript follows a simple object-oriented structure. Objects are an entity with values and properties. It comprises a key and value pair describing a certain ‘property.’ For example, we can consider a laptop a simple object with properties such as the company name, the processor, the OS, the model, and so on. This can be made into an object in JavaScript like:

let laptop = {
         companyName: ‘HP’,
         processor: ‘11th Intel(R) Core(TM) Gen i5’,
         OS: ‘Windows 11’,
 }

Although JSON was created as a subset of JavaScript, since it uses objects and arrays to represent data, it does not restrict to any specific language. Any object-oriented language can use JSON.

See Also: What is the Proper Operator for “Not Equals” in JavaScript?

How is data expressed in JSON?

The datatypes supported by JSON restricts to strings, numbers, objects, arrays, Boolean literals( true and false ), and null. When the data transfers between the web page and the server, it is done in the form of strings. So, by implementing JSON, which compacts the data and uses different formats to describe the different data types, data transfer becomes much faster and much more manageable.

JSON data expression

JSON uses ‘{}’(curly brackets) to describe objects, ‘[]’(third brackets) to describe arrays, and strings are expressed with double quotations and numeric values without quotations. It uses commas to separate the different key-value pairs. Only literals, like true, false, and null, are written without quotation marks. In JavaScript, we can use double and single quotations interchangeably, whereas, in JSON, we use only double quotations. For example, a person’s data can be expressed like:

{
         “name”: “Sanguthevar”,
         “age”: 25,
        “qualifications”: [“ICSE”, “ISC”, “BTech”, “MTech”, “MS + Phd”],
         “Researcher”: true,
         “Issues Raised”: null
}

Conversion of JavaScript Objects to JSON

JSON.stringify() function converts any object in JavaScript to JSON.

JavaScript objects to JSON

 

For example, we can create an array in JavaScript, and the following is how we convert it to JSON.

const array = [“Cup”, “Plate”, “Tea”, “Biscuit”];
const newJson = JSON.stringify(array);

Now, this newJson has been converted to a whole string and can be sent directly to the server as one.

Implementation on an object:
const info = {name: ‘Sanguthevar’, age: 25, city: ‘Lucknow’};
const newJson= JSON.stringify(info);

Since we have converted the object to JSON, we must store it somewhere. We can use the function localStorage.setItem(nameToStoreAs, newJson) or directly store the data on the server using the database or file system.

We can use database management systems such as MySQL and MongoDB to store the data and then use SQL queries to retrieve the data. If we take the help of a file system, we save data in a JSON file, and then we write and edit the data on the server’s file system itself. Then we can convert it to JavaScript and put the data on our web pages.

Conversion of JSON file to JavaScript

A JSON file can be converted back to JavaScript by using JSON.parse(). We can take the JSON file from where it is stored and use this function on the opened file. This is also a widespread use of JSON, where we take some data files from the server and then display it on the webpage.

JSON to JavaScript

Continuing with the last example,

const info = {name: ‘Sanguthevar’, age: 25, city: ‘Lucknow’};
const newJson= JSON.stringify(info);
//Storing the data directly on the local device
localStorage.setItem(personInfo, newJson);
//Opening the data file on the local device
let obj = localStorage.getItem(personInfo);
let display = JSON.parse(obj)
document.getElementById(“ details ”).innerHTML = display.name;
//Here, we assume we have used a div or a paragraph in the HTML file with the id as “details.”

To elaborate, here is the snippet of the HTML file:

<html>
         <head>
                     <title>Conversion between JavaScript to JSON and Back</title>
         </head>
         <body>
                     <p id= “details”></p>
         </body>
         <script>
                     const info = {name: ‘Sanguthevar’, age: 25, city: ‘Lucknow’};
const newJson= JSON.stringify(info);
//Storing the data directly on the local device
localStorage.setItem(personInfo, newJson);
//Opening the data file on the local device
let obj = localStorage.getItem(personInfo);
let display = JSON.parse(obj)
document.getElementById(“ details ”).innerHTML = display.name;
         </script>
</html>

FAQS

What are the advantages of using JSON?

JSON has several advantages, including its simplicity, flexibility, and compatibility with various programming languages and technologies. It is also easy to parse and generate, making it an ideal choice for web APIs and other types of data exchange.

How is data represented in JSON?

Data in JSON is represented using key-value pairs, similar to how objects are represented in many programming languages. A comma separates each key-value pair, and the entire data structure is enclosed in curly braces.

What basic types of values does JSON support?

JSON supports six basic types of values: strings, numbers, booleans, null, arrays, and objects. Strings are enclosed in double quotes, numbers can be integers or floating point values, booleans are represented as 'true' or 'false', and null is represented as 'null'.

What is an array in JSON?

An array in JSON is an ordered collection of values, separated by commas and enclosed in square brackets. Arrays can contain values of any type, including other arrays and objects.

What is an object in JSON?

An object in JSON is an unordered collection of key-value pairs, separated by commas and enclosed in curly braces. Objects can contain values of any type, including other arrays and objects.

How is data accessed in JSON?

Data in JSON is accessed using dot notation or bracket notation. Dot notation is used to access object properties, while bracket notation is used to access array elements.

Also, explore 6 ways to convert an array to an object in JavaScript. 

Conclusion

In this fast-paced world where everything is automated and the internet has become an essential part of survival, JSON has become extremely necessary owing to its lightweight and dynamic nature.

By mastering the techniques for formatting numbers with commas in JavaScript, developers can present data in a clear and organized manner, making it easier for users to interpret and analyze.

Learning how to read a JSON file in JavaScript is essential for web developers who work with data-driven applications.

See Also: How To Convert String To Date In Javascript In Dd-Mm-Yyyy Format

See also: How To Use List Filter In Javascript?

Leave a Comment