JSON.parse() (2024)

A common use of JSON is to exchange data to/from a web server.

When receiving data from a web server, the data is always a string.

Parse the data with JSON.parse(), and the data becomes a JavaScript object.

Example - Parsing JSON

Imagine we received this text from a web server:

'{"name":"John", "age":30, "city":"New York"}'

Use the JavaScript function JSON.parse() to convert text into a JavaScript object:

const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');

Make sure the text is in JSON format, or else you will get a syntax error.

Use the JavaScript object in your page:

Example

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = obj.name;
</script>

Try it Yourself »

Array as JSON

When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.

Example

const text = '["Ford", "BMW", "Audi", "Fiat"]';
const myArr = JSON.parse(text);

Try it Yourself »

Exceptions

Parsing Dates

Date objects are not allowed in JSON.

If you need to include a date, write it as a string.

You can convert it back into a date object later:

Example

Convert a string into a date:

const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text);
obj.birth = new Date(obj.birth);

document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;

Try it Yourself »

Or, you can use the second parameter, of the JSON.parse() function, called reviver.

The reviver parameter is a function that checks each property, before returning the value.

Example

Convert a string into a date, using the reviver function:

const text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
const obj = JSON.parse(text, function (key, value) {
if (key == "birth") {
return new Date(value);
} else {
return value;
}
});

document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;

Try it Yourself »

Parsing Functions

Functions are not allowed in JSON.

If you need to include a function, write it as a string.

You can convert it back into a function later:

Example

Convert a string into a function:

const text = '{"name":"John", "age":"function () {return 30;}", "city":"New York"}';
const obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");

document.getElementById("demo").innerHTML = obj.name + ", " + obj.age();

Try it Yourself »

You should avoid using functions in JSON, the functions will lose their scope, and you would have to use eval() to convert them back into functions.


W3schools Pathfinder

Track your progress - it's free!

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.

JSON.parse() (2024)

FAQs

What does the JSON parse () method? ›

JSON.parse() The JSON.parse() static method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

What is the difference between JSON() and JSON parse()? ›

The difference is: json() is asynchronous and returns a Promise object that resolves to a JavaScript object. JSON. parse() is synchronous can parse a string to (a) JavaScript object(s).

What is parse() in JavaScript? ›

The parse method in JavaScript is used to convert a JSON string into a JavaScript object. JSON stands for JavaScript Object Notation and is a lightweight data interchange format. Here is an example of how to use the parse method: javascript.

How do I parse a JSON file? ›

If we have a JSON string, we can parse it by using the json.loads() method. json.loads() does not take the file path, but the file contents as a string, to read the content of a JSON file we can use fileobject.read() to convert the file into a string and pass it with json.loads().

Why do we need to parse JSON? ›

Before you can use the data inside the text, you will have to parse the JSON. After parsing, the data is an object or an array with objects on which you can operate: sort by price or relevance, count the number of results, and map different properties like product name, and description to the user interface.

What is the result of JSON parse? ›

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

When to use JSON parse and stringify? ›

parse() converts JSON strings to JavaScript objects, while JSON. stringify() converts JavaScript objects to JSON strings.

How does JSON parser work? ›

A JSON (JavaScript Object Notation) parser is a program that reads a JSON-formatted text file and converts it into a more easily usable data structure, such as a dictionary or a list in Python or an object in JavaScript.

Is it easier to parse JSON or XML? ›

You need to parse XML with an XML parser. JSON is simple and more flexible. XML is complex and less flexible. JSON supports numbers, objects, strings, and Boolean arrays.

What is an example of parsing? ›

"The woman with the sparkly black backpack is my sister." In this example, we can see two main constituents: the subject (The woman with the sparkly black backpack) and its predicate (is my sister). Parsing helps us to recognize which group of words is the subject and which ones are the predicate.

What does parse do? ›

Parsing means analyzing and converting a program into an internal format that a runtime environment can actually run, for example the JavaScript engine inside browsers. The browser parses HTML into a DOM tree.

What is a JSON parse error? ›

Parse errors occur when your JSON file has incorrect syntax, such as a missing comma or misplaced bracket. It's like a grammatical error in a sentence that makes it difficult to understand. Format issues, on the other hand, occur when the JSON structure does not conform to the specification.

What is the best way to parse JSON? ›

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

How to access data in JSON parse? ›

Parse JSON data

To access data within a JSON array, you can use array indexing, while to access data within an object, you can use key-value pairs. In the example above, there is an object 'car' inside the JSON structure that contains two mappings ('model' and 'year').

How to extract data from JSON? ›

To extract an entire JSON object from a list, pass the valid index of the object to the function, using the . (dot) notation: [ColumnName]. fieldName[i] [ColumnName].

What does JSON() do? ›

Response: json() method

It returns a promise which resolves with the result of parsing the body text as JSON . Note that despite the method being named json() , the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object.

What does JSON parse and JSON Stringify do? ›

JSON. parse() is used for parsing data that was received as JSON; it deserializes a JSON string into a JavaScript object. JSON. stringify() on the other hand is used to create a JSON string out of an object or array; it serializes a JavaScript object into a JSON string.

How does JSON parser work in Java? ›

Parsing JSON allows Java developers to convert JSON data into Java objects or extract specific values from the JSON structure. Some potential reasons for asking this question include: – Needing to consume JSON data from an external API.

What is the JSON parse JSON Stringify function? ›

JSON. stringify() : This method takes a JavaScript object and then transforms it into a JSON string. JSON. parse() : This method takes a JSON string and then transforms it into a JavaScript object.

Top Articles
webtoons.com Website Traffic, Ranking, Analytics [August 2024]
California's Common Carrier Accident Law | LA Century Law
Poe T4 Aisling
neither of the twins was arrested,传说中的800句记7000词
Lowe's Garden Fence Roll
It may surround a charged particle Crossword Clue
Live Basketball Scores Flashscore
Access-A-Ride – ACCESS NYC
1970 Chevelle Ss For Sale Craigslist
Here are all the MTV VMA winners, even the awards they announced during the ads
Otis Department Of Corrections
Richard Sambade Obituary
Tap Tap Run Coupon Codes
Violent Night Showtimes Near Amc Fashion Valley 18
Blue Ridge Now Mugshots Hendersonville Nc
Med First James City
Superhot Unblocked Games
Summoners War Update Notes
“In my day, you were butch or you were femme”
Nyuonsite
Google Feud Unblocked 6969
Ou Class Nav
Check From Po Box 1111 Charlotte Nc 28201
Costco Gas Foster City
Everything We Know About Gladiator 2
Aris Rachevsky Harvard
Leccion 4 Lesson Test
Ahrefs Koopje
Ge-Tracker Bond
Puss In Boots: The Last Wish Showtimes Near Cinépolis Vista
Aerocareusa Hmebillpay Com
Touchless Car Wash Schaumburg
Providence Medical Group-West Hills Primary Care
Little Rock Skipthegames
Holiday Gift Bearer In Egypt
Trivago Myrtle Beach Hotels
Select Truck Greensboro
Nk 1399
Dreamcargiveaways
Diana Lolalytics
All Things Algebra Unit 3 Homework 2 Answer Key
Barrage Enhancement Lost Ark
Daily Jail Count - Harrison County Sheriff's Office - Mississippi
Cl Bellingham
Www Usps Com Passport Scheduler
Guy Ritchie's The Covenant Showtimes Near Grand Theatres - Bismarck
Nina Flowers
13 Fun &amp; Best Things to Do in Hurricane, Utah
Tom Kha Gai Soup Near Me
3500 Orchard Place
Muni Metro Schedule
Dinargurus
Latest Posts
Article information

Author: Twana Towne Ret

Last Updated:

Views: 6046

Rating: 4.3 / 5 (64 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Twana Towne Ret

Birthday: 1994-03-19

Address: Apt. 990 97439 Corwin Motorway, Port Eliseoburgh, NM 99144-2618

Phone: +5958753152963

Job: National Specialist

Hobby: Kayaking, Photography, Skydiving, Embroidery, Leather crafting, Orienteering, Cooking

Introduction: My name is Twana Towne Ret, I am a famous, talented, joyous, perfect, powerful, inquisitive, lovely person who loves writing and wants to share my knowledge and understanding with you.