Parsing a json object in javascript

JSON .parse()

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:

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

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

Use the JavaScript object in your page:

Читайте также:  Python mysql datetime to datetime

Example

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

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:

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

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:

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

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:

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

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.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

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.

Источник

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.

Try it

Syntax

JSON.parse(text) JSON.parse(text, reviver) 

Parameters

The string to parse as JSON. See the JSON object for a description of JSON syntax.

If a function, this prescribes how each value originally produced by parsing is transformed before being returned. Non-callable values are ignored. The function is called with the following arguments:

The key associated with the value.

The value produced by parsing.

Return value

The Object , Array , string, number, boolean, or null value corresponding to the given JSON text .

Exceptions

Thrown if the string to parse is not valid JSON.

Description

JSON.parse() parses a JSON string according to the JSON grammar, then evaluates the string as if it’s a JavaScript expression. The only instance where a piece of JSON text represents a different value from the same JavaScript expression is when dealing with the «__proto__» key — see Object literal syntax vs. JSON.

The reviver parameter

If a reviver is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value and all its properties (in a depth-first fashion, beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver .

The reviver is called with the object containing the property being processed as this , and two arguments: key and value , representing the property name as a string (even for arrays) and the property value. If the reviver function returns undefined (or returns no value — for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value. If the reviver only transforms some values and not others, be certain to return all untransformed values as-is — otherwise, they will be deleted from the resulting object.

Similar to the replacer parameter of JSON.stringify() , reviver will be last called on the root object with an empty string as the key and the root object as the value . For JSON text parsing to primitive values, reviver will be called once.

Note that reviver is run after the value is parsed. So, for example, numbers in JSON text will have already been converted to JavaScript numbers, and may lose precision in the process. To transfer large numbers without loss of precision, serialize them as strings, and revive them to BigInts, or other appropriate arbitrary precision formats.

Examples

Using JSON.parse()

JSON.parse("<>"); // <> JSON.parse("true"); // true JSON.parse('"foo"'); // "foo" JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] JSON.parse("null"); // null 

Using the reviver parameter

JSON.parse( '', (key, value) => typeof value === "number" ? value * 2 // return value * 2 for numbers : value, // return everything else unchanged ); // JSON.parse('>>', (key, value) =>  console.log(key); return value; >); // 1 // 2 // 4 // 6 // 5 // 3 // "" 

Using reviver when paired with the replacer of JSON.stringify()

In order for a value to properly round-trip (that is, it gets deserialized to the same original object), the serialization process must preserve the type information. For example, you can use the replacer parameter of JSON.stringify() for this purpose:

// Maps are normally serialized as objects with no properties. // We can use the replacer to specify the entries to be serialized. const map = new Map([ [1, "one"], [2, "two"], [3, "three"], ]); const jsonText = JSON.stringify(map, (key, value) => value instanceof Map ? Array.from(value.entries()) : value, ); console.log(jsonText); // [[1,"one"],[2,"two"],[3,"three"]] const map2 = JSON.parse(jsonText, (key, value) => key === "" ? new Map(value) : value, ); console.log(map2); // Map < 1 =>"one", 2 => "two", 3 => "three" > 

Because JSON has no syntax space for annotating type metadata, in order to revive values that are not plain objects, you have to consider one of the following:

  • Serialize the entire object to a string and prefix it with a type tag.
  • «Guess» based on the structure of the data (for example, an array of two-member arrays)
  • If the shape of the payload is fixed, based on the property name (for example, all properties called registry hold Map objects).

JSON.parse() does not allow trailing commas

// both will throw a SyntaxError JSON.parse("[1, 2, 3, 4, ]"); JSON.parse(''); 

JSON.parse() does not allow single quotes

// will throw a SyntaxError JSON.parse(""); 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 12, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

How to Parse JSON in JavaScript — A Complete Guide

JSON is a popular text-based data format that is used to transmit data in network requests. JSON has an easy-to-read syntax and it’s a lightweight data format. This is what makes JSON such a favorable data format.

As a web developer, dealing with JSON is almost impossible to avoid. When dealing with JSON, one of the most common tasks you need to do is parse the JSON data and handle potential errors.

This is a comprehensive guide to JSON parsing in JavaScript.

If you’re looking for a quick answer, use the JSON.parse() function.

const person = `< "name": "Alice", "age": 26, "city": "New York" >`; const personObj = JSON.parse(person); console.log(personObj.name); console.log(personObj.age); console.log(personObj.city);

JSON.parse() — How to Parse JSON in JavaScript

JavaScript has a built-in method JSON.parse() for parsing JSON strings. This method constructs a JavaScript object from a JSON string input.

As a matter of fact, based on the input JSON, the JSON.parse() function can return an Object, Array, string, number, boolean, or null.

There are two ways to call the JSON.parse() method:

The first approach is more common as you simply convert a JSON string to a JavaScript object. The second approach involves an optional reviver function.

Let’s take a closer look at the two main ways to call the JSON.parse() function.

1. JSON.parse(text)

The simplest and the most common way to call the JSON.parse() function in JavaScript is by passing it a JSON string argument.

For example, let’s parse a simple JSON string that represents a pet:

const pet = '' const petObj = JSON.parse(pet); console.log(petObj.name); console.log(petObj.age);

The result of calling the JSON.parse() function this way returns a JavaScript object via which you can access the JSON key-value pairs with the dot notation.

Here are more examples that illustrate what different types of text inputs cause the JSON.parse() function to return.

JSON.parse("<>") // <> JSON.parse("false") // false JSON.parse('"Hello"') // "Hello" JSON.parse('[20,"Test",false]') // [ 20, 'Test', false ] JSON.parse("null") // null

2. JSON.parse(text, reviver)

Another way to call the JSON.parse() function is by passing it a second optional argument called reviver The idea of the reviver function is to perform an operation for the key-value pairs in the JSON data.

If you specify a reviver function, you must call it with the arguments

  1. key. The key related to the value processed by the reviver.
  2. value. The value associated with the processed key.

Here’s the syntax for calling the JSON.parse() function with a reviver function:

To make any sense of these, you will need to see some examples.

For example, let’s convert the value associated with a key “age” to days. To do this, you need to specify a reviver function. The reviver multiplies the value by 365.25 if its key is “age” and the value is a number.

Here’s what the code looks like:

const pet = '' const petObj = JSON.parse(pet, (key, value) => < if (key === "age" && typeof value === "number") < return value * 365.25 >else < return value >>); console.log(petObj.name); console.log(petObj.age);

Now the age of the pet is expressed in days rather than years. (Notice how the name property remains untouched thanks to the if-else statement in the reviver function).

Limitations with JSON.parse() Function

There are two main limitations with the JSON.parse() function:

  1. JSON.parse() doesn’t accept trailing commas.
  2. JSON.parse() doesn’t accept single-quotes.

So for example, this piece of code fails due to a trailing comma:

SyntaxError: Unexpected token > in JSON at position 13

As another example, parsing JSON with single quotes fails too:

SyntaxError: Unexpected token ' in JSON at position 1

Summary

Today you learned how to parse JSON in JavaScript.

To recap, use the built-in JSON.parse() function to parse JSON data by passing the JSON object as an argument to this function.

Thanks for reading. Happy coding!

Read Also

About the Author

Hi, I’m Artturi Jalli!

I’m a Tech enthusiast from Finland.

I make Coding & Tech easy and fun with well-thought how-to guides and reviews.

I’ve already helped 5M+ visitors reach their goals!

ChatGPT Review (and How to Use It)—A Full Guide (2023)

ChatGPT is the newest Artificial Intelligence language model developed by OpenAI. Essentially, ChatGPT is an AI-based chatbot that can answer any question. It understands complex topics, like.

10 Best AI Art Generators of 2023 (Reviewed & Ranked)

Choosing the right type of AI art generator is crucial to produce unique, original, and professional artwork. With the latest advancements in AI art generation, you can.

How to Make an App — A Complete 10-Step Guide (in 2023)

Are you looking to create the next best-seller app? Or are you curious about how to create a successful mobile app? This is a step-by-step guide on.

9 Best Graphic Design Courses + Certification (in 2023)

Do you want to become a versatile and skilled graphic designer? This is a comprehensive article on the best graphic design certification courses. These courses prepare you.

8 Best Python Courses with Certifications (in 2023)

Are you looking to become a professional Python developer? Or are you interested in programming but don’t know where to start? Python is a beginner-friendly and versatile.

8 Best Swift & iOS App Development Courses [in 2023]

Are you looking to become an iOS developer? Do you want to create apps with an outstanding design? Do you want to learn to code? IOS App.

Источник

Оцените статью