JavaScript JSON Object

What is JSON?

JSON stands for JavaScript Object Notation. It 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 a text-based format that is often used to represent structured data, and it is commonly used for data exchange between a server and a web application, as well as for configuration files and data storage.

in a simple way JSON  is like a special language that computers understand and use to talk to each other. It’s a way to organize and store information in a very neat and organized way

JSON data is represented using two main structures:

  • Object
  • Array

Why JSON Object is important in JavaScript ?

  1. Data Exchange: JSON is widely used for data exchange between a web server and a client-side JavaScript application. It provides a structured way to send and receive data, making it easy to transmit complex data structures.

  2. APIs: Many web APIs (Application Programming Interfaces) use JSON as the standard data format for sending and receiving data. This allows different systems and programming languages to communicate seamlessly.

  3. Configuration: JSON is often used for configuration files in web applications. It provides a simple and human-readable format for specifying settings and options.

  4. Data Storage: JSON is used for storing data in NoSQL databases, such as MongoDB. Its flexible and hierarchical structure makes it a good choice for storing and querying data.

  5. JavaScript Integration: JSON is a natural fit for JavaScript because it closely resembles JavaScript object and array literals. This makes it easy to work with JSON data in JavaScript code.

JSON SYNTAX

Data is in Key-Value Pairs: JSON organizes data into key-value pairs. A key is a string that acts like a label, and a value can be a string, number, boolean, null, object, or array.

{
“name”: “John”,
“age”: 30,
“isStudent”: false,
“city”: null
}

 

 
 
Json Object in JavaScript
Objects are Enclosed in Curly Braces { }: JSON objects are enclosed in curly braces. Each key-value pair is separated by a comma.
 
Arrays are Enclosed in Square Brackets []: JSON arrays are ordered lists of values enclosed in square brackets. Values in an array are also separated by commas.
{
"fruits": ["apple", "banana", "cherry"]
}

Strings are Enclosed in Double Quotes:Keys and string values must be enclosed in double quotes.

{
"name": "Alice"
}

Numbers:JSON supports both integers and floating-point numbers.

{
"age": 25,
"price": 2.99
}

Booleans: JSON represents true and false values as true and false (without quotes).

{
"isStudent": true
}

Null: JSON uses null (without quotes) to represent a null or empty value.

{
"city": null
}

Whitespace: JSON ignores whitespace characters (like spaces and line breaks) outside of strings. However, it’s recommended to format JSON for readability.
Nesting: You can nest objects and arrays within each other to create complex data structures.

{
"person": {
"name": "Bob",
"age": 35
},
"hobbies": ["reading", "hiking"]
}

Accessing JSON Data

Think of JSON objects like boxes with labels (keys) on them, and these boxes can contain various things (values). JSON arrays are like lists of items.

Dot Notation: 

 Dot notation is like directly looking at the labels on the boxes.
    You can use dot notation when you know the label (key) you want to check.
    It’s like saying, “Tell me what’s in the ‘name’ box.”

Example with Dot Notation:

const person = {
  name: "John",
  age: 30
};
const personName = person.name; // Here, we're looking directly at the 'name' label and getting "John."

 

Bracket Notation

Bracket notation is like asking someone to tell you what’s in a particular box by describing the label to them.
You use square brackets [] and put the label (key) inside quotes to access the box.
It’s helpful when you don’t know the label beforehand or when labels have special characters or spaces.

const person = {
  name: "John",
  age: 30
};

const key = "name";
const personName = person[key]; // Here, we're describing the 'name' label to access what's inside the box.

Accessing Values in Arrays:

Think of JSON arrays like a line of numbered boxes, starting from 0.

    You can get what’s inside a box by telling which number (index) it is.
    It’s like saying, “Give me the thing in the first box.”

 

Example with Array:

				
					const fruits = ["apple", "banana", "cherry"];
const firstFruit = fruits[0]; // Here, we're asking for what's in the first box, which is "apple."
				
			

Functions for Working with JSON

JSON.stringify()

The JSON.stringify() function converts an object to a JSON string.

Strings are useful for transporting data from a client to a server through storing or passing information in a lightweight way. For example, you may gather a user’s settings on the client side and then send them to a server. Later, you can then read the information with the JSON.parse() method and work with the data as needed.

We’ll look at a JSON object that we assign to the variable obj, and then we’ll convert it using JSON.stringify() by passing obj to the function. We can assign this string to the variable s:

				
					var obj = {"first_name" : "Sammy", "last_name" : "Shark", "location" : "Ocean"}

var d = JSON.stringify(obj)
				
			

Now, if we work with d, we’ll have the JSON available to us as a string rather than an object.

				
					'{"first_name" : "Sammy", "last_name" : "Shark", "location" : "Ocean"}'
				
			

The JSON.stringify() function lets us convert objects to strings. To do the opposite, we’ll look at the JSON.parse() function.

JSON.parse()

Strings are useful for transporting but you’ll want to be able to convert them back to a JSON object on the client and/or the server side. We can do this using the JSON.parse() function.

To convert the example in the JSON.stringify() section above, we would pass the string s to the function, and assign it to a new variable:

				
					var o = JSON.parse(s)
				
			

Then, we would have the object o to work with, which would be identical to the object obj.To take a deeper look, let’s consider an example of JSON.parse() within the context of an HTML file

				
					<!DOCTYPE html>
<html>
<body>

<p id="user"></p> <script src="data:text/javascript;base64,dmFyIHM9J3siZmlyc3RfbmFtZSIgOiAiS2F1c2FsIiwgImxhc3RfbmFtZSIgOiAiUmFvIiwgImxvY2F0aW9uIiA6ICJNdW1iYWkifSc7dmFyIG9iaj1KU09OLnBhcnNlKHMpO2RvY3VtZW50LmdldEVsZW1lbnRCeUlkKCJ1c2VyIikuaW5uZXJIVE1MPSJOYW1lOiAiK29iai5maXJzdF9uYW1lKyIgIitvYmoubGFzdF9uYW1lKyI8YnI+IisiTG9jYXRpb246ICIrb2JqLmxvY2F0aW9u" defer></script> <script data-no-optimize="1">var litespeed_vary=document.cookie.replace(/(?:(?:^|.*;\s*)_lscache_vary\s*\=\s*([^;]*).*$)|^.*$/,"");litespeed_vary||fetch("/wp-content/plugins/litespeed-cache/guest.vary.php",{method:"POST",cache:"no-cache",redirect:"follow"}).then(e=>e.json()).then(e=>{console.log(e),e.hasOwnProperty("reload")&&"yes"==e.reload&&(sessionStorage.setItem("litespeed_docref",document.referrer),window.location.reload(!0))});</script></body>
</html>
				
			

output:-  Name: Kaushal Rao
                     Location: Mumbai
Within the context of an HTML file, we can see how the JSON string s is converted to an object that is retrievable on the final rendering of the page by accessing the JSON via dot notation.

JSON.parse() is a secure function to parse JSON strings and convert them to objects. 

Json Object is one of the most powerful feature in JavaScript widely used for exchanging data over internet. I tired my best to keep is simple and basics. Hope you enjoyed. Have a great time…

Leave a Reply

Your email address will not be published. Required fields are marked *