DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Dynamic Web Forms In React For Enterprise Platforms
  • An Introduction to Object Mutation in JavaScript
  • Metaprogramming With Proxies and Reflect in JavaScript
  • Custom Elements Manifest: The Key to Seamless Web Component Discovery and Documentation

Trending

  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  1. DZone
  2. Coding
  3. JavaScript
  4. A Comprehensive Guide To Working With JSON in JavaScript

A Comprehensive Guide To Working With JSON in JavaScript

This tutorial covers everything you need to know about working with JSON objects in JavaScript. It includes topics such as creating, parsing, and manipulating JSON data.

By 
Deepa Ajish user avatar
Deepa Ajish
·
Nov. 29, 23 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
3.7K Views

Join the DZone community and get the full member experience.

Join For Free

What Is a JSON Object?

JSON stands for Javascript Object Notation and is a standard text-based format for representing structured data based on JavaScript object syntax. JSON defines only two data structures: objects and arrays. JSON object is a data type that consists of key/value pairs surrounded by curly braces. JSON array is a list of values. JSON objects are often used when data is sent from a server to a webpage or when data is stored in files or databases. JSON closely resembles Javascript object literal syntax but can be used independently from Javascript. Many programming environments support reading and generating JSON.

Features of JSON Objects

  • They are written in key/value pairs, separated by commas. A key is a string enclosed in double quotes, and a value must be a JSON data type as below
    • string
    • number
    • object
    • array
    • boolean
    • null
  • They are surrounded by curly braces {}. Curly braces can also be used to nest objects within objects, creating a hierarchical structure.
  • Arrays are enclosed in brackets [], and their values are separated by a comma (,). Each value in an array may be of a different type, including another array or an object.
  • They are case-sensitive, meaning the keys and values must match exactly in spelling and capitalization.
  • They don’t allow trailing commas. In simple terms, there should not be any text outside the curly braces or inside the double quotes that are not part of the key/value pairs.
  • They don’t allow comments.

JSON offers several benefits, making it a popular choice for representing structured data:

  • Simplicity and readability: JSON is straightforward and easy to understand. Unlike more verbose formats like XML, JSON is relatively easy to read as-is. Its concise syntax allows for efficient data representation.
  • Ease of parsing: JSON is simpler and faster to parse than XML. 
  • Flexibility: JSON supports various data types and object hierarchies, and relationships can be preserved during transmission and reassembled appropriately at the receiving end.
  • Widespread usage: Most modern APIs accept JSON requests and issue JSON responses, making it universal for data exchange between systems

Examples of JSON Objects

Basic JSON object: {"name": "Natalie", "married": false, "age": 21, "city": "New York", "zip" : "10001", "awards": null}

Nested JSON object: It is a data type that consists of a list of name/value pairs, where one or more of the values are another JSON object.

{"person": {"name": "Natalie", "age": 21}, "address": {"street": "123 XYZ Street", "City": "New York", "State" : "NY", "zip": "10001"}}

Array of JSON object:  [ { "name": "Natalie", "age": 21 }, { "name": "David", "age": 37 }, { "name": "Mark", "age": 43 } ]

 

Parsing JSON Objects

Parsing is the method of converting a JSON object into a native Javascript object.

JSON.parse() method: The JSON.parse() method parses a string and returns a Javascript object. The string has to be in JSON format. 

Syntax: JSON.parse(string, function)

Parameter 

Required/Optional

Description

String

Required

A string written in JSON format

Reviver function

Optional

A function that takes a key and a value as parameters and returns a modified value or undefined to delete the property. The function is called for each item. Any nested objects are transformed before the parent.

  

Example

JSON
 
var text = '{"name": "Natalie", "married": false, "age": 21, "city": "New York", "zip" : "10001", "awards": null}';                          
var obj = JSON.parse(text, function (key, value) {
     if (key === "name") {
       return value.toUpperCase();
     } else {
       return value;
     }
});
console.log(obj);


Output

JSON
 
{
     name: 'NATALIE',
     married: false,
     age: 21,
     city: 'New York',
     zip: '10001',
     awards: null
}


JSON.stringify() Method

This method converts Javascript objects into strings. When sending data to a web server the data has to be a string. JSON.stringify() also works with arrays.

Syntax: JSON.stringify(obj, replacer, space)

Parameter

Required/Optional

Description

Obj

Required

The value to convert to a string

Replacer

Optional

A function or an array used to transform the result. The replacer is called for each item.

Space

Optional

A string to be used as white space (max 10 characters), or a number, from 0 to 10, to indicate how many space characters to use as white space.

 

Example

JSON
 
var obj = {"name": "Natalie", "married": false, "age": 21, "city": "New York", "zip" : "10001", "awards": null};                              
var text = JSON.stringify(obj, function (key, value) {
     if (key === "name") {
       return value.toUpperCase();
     } else {
       return value;
     }
});
console.log(text);


Output

{"name":"NATALIE","married":false,"age":21,"city":"New York","zip":"10001","awards":null}

JSON
 
/*Insert the word SPACE for each white space:*/
var newText = JSON.stringify(obj, null, "space");
console.log(“Text with the word space “+ newText);


Output

JSON
 
Text with the word space {
space"name": "Natalie",
space"married": false,
space"age": 21,
space"city": "New York",
space"zip": "10001",
space"awards": null
}


Navigation of JSON Objects

The dot (.) or bracket ([]) notation can be used to navigate into its properties and access their values.

JSON
 
// Access the name using dot notation
var obj = {"name": "Natalie", "married": false, "age": 21, "city": "New York", "zip" : "10001", "awards": null};                             
console.log(obj.name);                      Output: Natalie


JSON
 
// Access the city using dot notation
console.log(obj["city"];                      Output: New York


JSON
 
var obj_array = [ { "name": "Natalie", "age": 21 }, { "name": "David", "age": 37 }, { "name": "Mark", "age": 43 } ]


JSON
 
// Access the first member's name using dot and bracket notation
console.log(obj_array[0].name);       Output: Natalie


JSON
 
// Access the second member's age using dot and bracket notation

console.log(obj_array[1][ "age"]);     Output: 37

Object.keys() Method

keys() method returns an array of a given object’s own enumerable string-keyed property names. The keys() method, being a static method, is called using the Object class name.

Syntax: Object.keys(obj)

Parameter

Required/Optional

Description

obj

Required

The object whose enumerable properties are to be returned                                                  

 

Object.values() Method

values() method returns an array of a given object’s own enumerable string-keyed property values. The values() method, being a static method, is called using the Object class name.

Syntax: Object.values(obj)

Parameter

Required/Optional

Description

obj

Required

The object whose enumerable properties are to be returned                                                  

 

Object.entries() Method

This method returns an array of key-value pairs of an object’s enumerable properties. The entries() method, being a static method, is called using the Object class name.

Syntax: Object.entries(obj)

Parameter

Required/Optional

Description

obj

Required

The object whose enumerable properties are to be returned                                                  

  

Example

JSON
 
var obj = {"name": "Natalie", "married": false, "age": 21, "city": "New York", "zip" : "10001", "awards": null};                              
var keys = Object.keys(obj);
var values = Object.values(obj);
var entries = Object.entries(obj);
console.log("Array of keys :");
console.log(keys);
console.log("Array of values :");
console.log(values);
console.log("Array of entries :");
console.log(entries);


Output

JSON
 
Array of keys :
[ 'name', 'married', 'age', 'city', 'zip', 'awards' ]
Array of values :
[ 'Natalie', false, 21, 'New York', '10001', null ]
Array of entries :
[
     [ 'name', 'Natalie' ],
     [ 'married', false ],
     [ 'age', 21 ],
     [ 'city', 'New York' ],
     [ 'zip', '10001' ],
     [ 'awards', null ]
]


for loop

A for loop repeats until a specified condition is evaluated to be false.

Syntax: for (initialization; condition; expression) {code block to be executed}

Parameter

Required/Optional

Description

Initialization

 

Required

Executed one time before the execution of the code block

Condition

Required

The condition for executing the code block

Expression

Required

Executed every time after the code block has been executed                                                 

 

Example

JSON
 
var obj = [ { "name": "Natalie", "age": 21, "married": true }, { "name": "David", "age": 37, "married": false }, { "name": "Mark", "age": 43, "married": true } ];
for(var i=0; i<obj.length; i++) {
           console.log("Name:  " + obj[i]["name"]); //using bracket notation
           console.log("Married Status:     " + obj[i].married); //using dot notation
}


Output

JSON
 
Output
Name:     Natalie
Married Status:  true
Name:     David
Married Status:  false
Name:     Mark
Married Status:  true

 

for…in Loop

The for...in statement iterates over all enumerable string non-symbol properties of an object including inherited enumerable properties. The code block inside the loop is executed once for each property.

Syntax: for (item in object) {code block to be executed}

Parameter

Required/Optional

Description

item

Required

A variable to iterate over the properties.                                                                                     

object

Required

The object to be iterated.


Example

JSON
 
var obj = [ { "name": "Natalie", "age": 21, "married": true }, { "name": "David", "age": 37, "married": false }, { "name": "Mark", "age": 43, "married": true } ];
for(item in obj) {
           console.log("Name:  " + obj[item]["name"]); //using bracket notation
           console.log("Married Status:     " + obj[item].married); //using dot notation
}


Output

JSON
 
Name:     Natalie
Married Status:  true
Name:     David
Married Status:  false
Name:     Mark
Married Status:  true


for…of Loop 

A for..of loop operates on the values sourced from an iterable object one by one in sequential order.

Syntax: array.forEach(variable of iterable object) {statement}

Parameter

Required/Optional

Description

Variable 

Required

For every iteration, the value of the next property is assigned to the variable. A variable can be declared with const, let, or var.

Iterable object

Required

The source of values on which the loop operates.

 

Example

JSON
 
var obj = [ { "name": "Natalie", "age": 21, "married": true }, { "name": "David", "age": 37, "married": false }, { "name": "Mark", "age": 43, "married": true } ];
for(var item of obj) {
           console.log("Name:  " + item["name"]); //using bracket notation
           console.log("Married Status:  " + item.married); //using dot notation
}


Output

JSON
 
Name:     Natalie
Married Status:  true
Name:     David
Married Status:  false
Name:     Mark
Married Status:  true


forEach() Method

The forEach() method calls a function for each element in an array. It must take at least one parameter which represents the elements of an array.

Syntax: array.forEach(function(currentValue, index, array), thisValue)

Parameter

Required/Optional

Description

Function 

Required

A function to run for each element of the array

currentvalue

Required

The value of the current element

index

Optional

Index of the current element

Array

Optional

Array of the current element

Thisvalue

Optional

A value passed to the function as this value. Default undefined.    

  

Example

JSON
 
var obj = [ { "name": "Natalie", "age": 21, "married": true }, { "name": "David", "age": 37, "married": false }, { "name": "Mark", "age": 43, "married": true } ];
obj.forEach((item, index, arr) => {
       console.log("Details of element:     " +index);
       console.log("Name:      "+arr[index]["name"]);
       console.log("Age:      "+item.age);
});


Output

JSON
 
Details of element:  0
Name:      Natalie
Age:      21
Details of element:  1
Name:      David
Age:      37
Details of element:  2
Name:      Mark
Age:      43


Conclusion

JSON is commonly employed for transmitting data between servers and web applications. The JSON’s flexibility, ease of parsing, and simplicity allow software developers to work with structured data efficiently in various programming environments.

JSON JavaScript Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Dynamic Web Forms In React For Enterprise Platforms
  • An Introduction to Object Mutation in JavaScript
  • Metaprogramming With Proxies and Reflect in JavaScript
  • Custom Elements Manifest: The Key to Seamless Web Component Discovery and Documentation

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!