Conversion of String to JSON in JavaScript

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.

Читайте также:  Data structures and algorithms with javascript

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.

Источник

Convert String to JSON

Convert String to JSON

Let us see about the Conversion of String to JSON, we know JSON serialization and deserialization, JSON stringify, JSON parser, etc. Conversion of String to JSON can be done in JavaScript, Java, Python and many other languages too. So, What do you mean by this conversion of String to JSON? JSON.parse method is used to convert the input string to JSON object by following some specifications. Convert String to JSON converts an input string to a JSON object for the user to have output in a readable format like a map or an array. This conversion is possible by JSON.parse() in JavaScript. In Java, the GSON object is used for conversion, whereas in Python, json.loads() is used for this conversion.

Web development, programming languages, Software testing & others

Syntax of Convert String to JSON

Given below is the syntax mentioned:

var obj = JSON.parse(string, function);

Arguments ‘string’ is a required parameter where a string is written in JSON format.

Reviver function is an optional parameter which is used to transform result. If this reviver function returns a valid value, the item value gets replaced with a transformed value. If, in case, the reviver returns undefined, then the item is deleted.

SyntaxError exception is thrown if the string to parse is not a valid JSON.

JSON syntax is a subset of JS syntax.

Conversion of String to JSON in JavaScript

JSON object, a data type in JS with properties and value pairs defined, JSON is data interchange formatter. Bunch of characters being formatted in various programs for easy communication, which returns JSON object corresponding to JSON text/ string.

var jsonSample = ‘’;
var obj = JSON.parse(jsonStr);
console.log(obj.employeeName); // prints “Amar”
console.log(jsonSample.employeeName); // prints undefined

When we convert string to JSON, the string gets parsed to a JSON object, which can be used anywhere in the code. Here, before parsing, it is a string, so data cannot be encoded. It gets converted to JS object on parsing, which makes it possible to access everywhere in the code.

Examples of Convert String to JSON

Given below are the examples of Convert String to JSON:

Example #1

const jsonSample = »;
const obj = JSON.parse(jsonSample);
console.log(obj.count);
console.log(obj.result);
console.log(JSON.parse(‘<>‘));
console.log(JSON.parse(‘true’));
console.log(JSON.parse(‘»amar»‘));
console.log(JSON.parse(‘[14, 45, «true»]’));
console.log(JSON.parse(‘null’));
//console.log(JSON.parse(‘[11, 22, 33, 44, ]’));
//console.log(JSON.parse(»));
//console.log(JSON.parse(«»));

Convert String to Json 1

In Java, we need to use Gson Library, a parser called JsonParser, which parses JSON string. Also, user can create a Gson instance and use the fromJson method. Gson is an open-source library for the conversion of string to Json in Java. Gson is responsible for its good performance.

Example #2


Parsing from JSON String



Convert String to Json 2

Example #3


Conversion of JSON string to date object



date object

So here, the Date function in JavaScript retrieves the date of birth in IST Indian Standard Time. Date objects are not allowed in JSON; hence we write it as a string and then convert or parse it to an object.

Example #4


Conversion of JSON string to function using parse



parse

As functions are not allowed in JSON, hence we include the function as a string and then parse it to a function. Functions lose their scope; eval () can be used to convert back to functions. As Json.parse() method in JavaScript converts JSON to JSON object. JSON is commonly used for exchanging data on server and web applications.

Example #5



style="border:solid 1px #CCC;padding:0 6px;"> 
[
"employeeID": "101",
"employeeName": "Saideep",
"employeeType": "SSE",
"employer": "Infy"
>,
"employeeID": "102",
"employeeName": "Karthick",
"employeeType": "SE",
"employer": "CG"
>,
"employeeID": "103",
"employeeName": "Meghana",
"employeeType": "TL",
"employer": "PWC"
>
]

Note: See the output in your browsers console window!



Convert String to Json 5

Convert String to Json 6

Conclusion

We have seen how the conversion of string to JSON is done in JavaScript, along with few examples illustrated above. Were able to gain theoretical knowledge in converting string to JSON in Java and Python languages. While receiving data from a server, data is in the form of a string, and sometimes this string may contain multiple fields embedded. To use each field, we will not be able to use it in string format, and hence input string is parsed so that it becomes easy to use embedded fields in the string. Hence parsing the input string or converting string to JSON is useful in developing software applications.

This is a guide to Convert String to JSON. Here we discuss the introduction, conversion of string to JSON in JavaScript and examples. You may also have a look at the following articles to learn more –

500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access

1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access

1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access

3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access

All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access

Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access

Источник

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