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:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

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
Capital One Venture Rewards Credit Card - The Points Guy
Prestamos Personales Sin Credito: A Path to Quick Cash
The Tribes and Castes of the Central Provinces of India, Volume 3
Canary im Test: Ein All-in-One Überwachungssystem? - HouseControllers
Culver's Flavor Of The Day Wilson Nc
Polyhaven Hdri
Sportsman Warehouse Cda
Jonathan Freeman : "Double homicide in Rowan County leads to arrest" - Bgrnd Search
Bloxburg Image Ids
Notary Ups Hours
Overzicht reviews voor 2Cheap.nl
My.doculivery.com/Crowncork
How Many Slices Are In A Large Pizza? | Number Of Pizzas To Order For Your Next Party
Samsung Galaxy S24 Ultra Negru dual-sim, 256 GB, 12 GB RAM - Telefon mobil la pret avantajos - Abonament - In rate | Digi Romania S.A.
Nwi Arrests Lake County
Dutch Bros San Angelo Tx
Procore Championship 2024 - PGA TOUR Golf Leaderboard | ESPN
Char-Em Isd
Arre St Wv Srj
Locate At&T Store Near Me
Army Oubs
Rural King Credit Card Minimum Credit Score
Jeff Now Phone Number
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Adt Residential Sales Representative Salary
Sussyclassroom
Synergy Grand Rapids Public Schools
Webworx Call Management
Watertown Ford Quick Lane
Bolly2Tolly Maari 2
Infinite Campus Asd20
Lindy Kendra Scott Obituary
Keshi with Mac Ayres and Starfall (Rescheduled from 11/1/2024) (POSTPONED) Tickets Thu, Nov 1, 2029 8:00 pm at Pechanga Arena - San Diego in San Diego, CA
Tracking every 2024 Trade Deadline deal
Shia Prayer Times Houston
Desales Field Hockey Schedule
Capital Hall 6 Base Layout
Nicole Wallace Mother Of Pearl Necklace
Ixl Lausd Northwest
Giantess Feet Deviantart
Autozone Locations Near Me
Caderno 2 Aulas Medicina - Matemática
Fifty Shades Of Gray 123Movies
Fetus Munchers 1 & 2
Craigs List Hartford
Ig Weekend Dow
Citizens Bank Park - Clio
Air Sculpt Houston
2121 Gateway Point
One Facing Life Maybe Crossword
Texas Lottery Daily 4 Winning Numbers
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.