To convert a JSON string into a JS object

How to convert a JSON string into a JavaScript object?

There are two possible ways to convert a JSON string into a Javascript object – eval() and parse(). The usage of eval() method is unsafe and not preferred. It is vulnerabable to hackers. The parse() method is preferred in general anytime.

The typical application for JSON is Data transfer to and from a web server. The data that has been sent from a server is always a JSON string. Using JSON.parse(), we can convert the JSON string into a JS object.

Syntax

The syntax on how to convert a JSON string into JS object is −

Where, text is the string whose value is to be converted into an object.

Example 1

In this example, we use parse() method to convert a JSON string to object. The dictionary is taken as a JSON string.

            

On executing the above code, the following output is generated.

Example 2

In this example, we use parse() method to convert a JSON string to object. The dictionary is taken as a JSON string.

            

On executing the above code, the following output is generated.

Example 3

The below example program illustrates about converting a JSON string into JS object where the date is given as a string in JSON string. Because JSON string does not accept Date objects.

        

convert a JSON string( where date is included as a string) into a JS object

On executing the above code, the following output is generated.

Источник

How to Convert JSON to JavaScript Object

JSON (JavaScript Object Notation) has become the de facto serialization format for REST APIs, due to the fact that it’s humanly-readable, simple and small in size.

It uses the same notation used to define JavaScript objects, and naturally, it’s extremely straightforward to convert between a JSON string and JavaScript objects.

We’ll be working with the following JSON string:

const jsonString = '"author" : "Plato", "name" : "Republic", "releaseYear" : "375BC">'; 

Convert JSON String to JavaScript Object

The JSON module offers two methods — stringify() , which turns a JavaScript object into a JSON String, and parse() , which parses a JSON string and returns a JavaScript object.

Читайте также:  What can you do with javascript injection

It’s built into the language itself so there’s no need to install or import any dependencies:

const book = JSON.parse(jsonString); console.log('Type: ', typeof book); console.log('Contents: ', book) 

You might be tempted to eval() a string into an object, but be weary of the practice:

const book = eval("(" + jsonString + ")") console.log('Type: ', typeof book); console.log('Contents: ', book) 

However, this method is also susceptible to code injection. eval() will evaluate and execute any arbitrary text that you put in, provided it can be run. If our jsonString was changed to:

const jsonString = 'console.log("Malicious code")'; 

Then just evaluating it would result in:

const book = eval("(" + jsonString + ")") // Malicious code 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

It is ultimately true that JavaScript runs, to a large degree, on the client’s machine, on which they can evaluate and run any code they’d like within the browser. However, a major paradigm shift has occured in recent years, and JavaScript is more and more being used on the server-side as well. Even though Code Injection security does ultimately fall on the server-side, since you can’t really prevent it on the front-end — there’s a chance JavaScript is running on the server-side as well.

Convert JSON String to JavaScript Array

Although you can parse JSON into any arbitrary object — a common data structure into which you’ll convert data are arrays. JSON arrays are contained within square brackets, and elements of arrays are separated by commas:

[element1, element2, element3] 

An element can be a standalone element, another JSON object or another array, which in turn can contain any of these types as well. Let’s take a look at two arrays — a simple one with a few elements, and one that contains several JSON objects:

const simpleArrayJson = '["Java", "Python", "JavaScript"]'; const objectArrayJson = '[,, ]'; const simpleArray = JSON.parse(simpleArrayJson); const objectArray = JSON.parse(objectArrayJson); console.log(simpleArray); console.log(objectArray); 

Conclusion

In this short tutorial, we’ve taken a look at how to convert a JSON string into a JavaScript object, and remarked at a bad practice that could introduce vulnerabilities in your code.

Источник

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.

Читайте также:  Дайте определения основным понятиям языка html

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.

Источник

Java Guides

Note that in the above example, we are passing JSON string to JSON.parse() method which returns JavaScript Object.

JSON.parse() Method — Detail Explanation

Syntax

Parameter Values

  • text — This is a required field. A string is written in JSON format
  • reviver function — This parameter an optional. A function used to transform the result.

An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

JSON.parse() Method Examples

var text = JSON.parse( '< "firstName" : "Ramesh", "lastName" : "Fadatare", "emailId" : "ramesh@gmail.com", "age" : "29" >'); console.log(text);
/*replace the value of "city" to upper case:*/ var text = '< "name":"John", "age":"39", "city":"New York">'; var obj = JSON.parse(text, function (key, value) < if (key == "city") < return value.toUpperCase(); > else < return value; > >); console.log(text);
JSON.parse('<>'); // <> JSON.parse('true'); // true JSON.parse('"foo"'); // "foo" JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] JSON.parse('null'); // null

Convert a JavaScript Object to JSON String

References

  • Get link
  • Facebook
  • Twitter
  • Pinterest
  • Email
  • Other Apps

Subscriber to my top YouTube Channel (120K+ Subscribers)

My Udemy Course: Building Microservices with Spring Boot and Spring Cloud

Spring Boot Thymeleaf Real-Time Web Application Course

My Udemy Course — Testing Spring Boot Application with JUnit and Mockito

My Udemy Course — Building Real-Time REST APIs with Spring Boot

My Udemy Course — Master Spring Data JPA with Hibernate

My Udemy Course — Spring Boot RabbitMQ Course — Event-Driven Microservices

My Udemy Course — Spring Boot + Apache Kafka Course

About Me

Hi, I am Ramesh Fadatare. I am VMWare Certified Professional for Spring and Spring Boot 2022.

I am founder and author of this blog website JavaGuides, a technical blog dedicated to the Java/Java EE technologies and Full-Stack Java development.

All the articles, guides, tutorials(2000 +) written by me so connect with me if you have any questions/queries. Read more about me at About Me.

Top YouTube Channel (75K+ Subscribers): Check out my YouTube channel for free videos and courses — Java Guides YouTube Channel

Источник

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