Use json string in javascript

How to decode and encode JSON Data in JavaScript

In this session, you will learn how to encode and decode JSON data in JavaScript with the help of an example.

What is JSON

JavaScript Object Notation also knew as JSON. Between server and client relationship JSON is used which is an extremely lightweight data-interchange format for data exchange and easy to parse and quick to generate. JSON is easy to write and understand for both humans and computers which is based on a text format.

Types of JSON

JSON depend upon two basic structures:

Parsing JSON Data in JavaScript

In JavaScript, by using JSON.parse( ) method you can easily data received from the webserver. In JSON string if the given string is not valid, the result you will get is a syntax error. As shown in the example:

By using the JSON.parse( ) method in JavaScript to convert the string into a JavaScript Object and access individual values by using the do notation (.), as shown in the example:

// Store JSON data in a JS variable var json = ''; // Converting JSON-encoded string to JS object var obj = JSON.parse(json); // Accessing individual value from JS object alert(obj.name); // Outputs: Peter alert(obj.age); // Outputs: 22 alert(obj.country); // Outputs: United States

Parsing Nested JSON Data in JavaScript

You can also nested JSON objects and arrays. In JavaScript, JSON objects can contain other JSON objects, nested arrays, arrays, arrays of the JSON object, and so on. In mention below example, you will learn how to extract all the values and parse a nested JSON in JavaScript.

/* Storing multi-line JSON string in a JS variable using the new ES6 template literals */ var json = ` < "book": < "name": "Harry Potter and the Goblet of Fire", "author": "J. K. Rowling", "year": 2000, "characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"], "genre": "Fantasy Fiction", "price": < "paperback": "$10.40", "hardcover": "$20.32", "kindle": "$4.11" >> >`; // Converting JSON object to JS object var obj = JSON.parse(json); // Define recursive function to print nested values function printValues(obj) < for(var k in obj) < if(obj[k] instanceof Object) < printValues(obj[k]); >else < document.write(obj[k] + "
"); >; > >; // Printing all the values from the resulting object printValues(obj); document.write("
"); // Printing a single value document.write(obj["book"]["author"] + "
"); // Prints: J. K. Rowling document.write(obj["book"]["characters"][0] + "
"); // Prints: Harry Potter document.write(obj["book"]["price"]["hardcover"]); // Prints: $20.32

Encoding Data as JSON in JavaScript

During an Ajax communication JavaScript object or value from your code sometime need to be transferred to the server. JavaScript provides a method that converts a JavaScript value to a JSON String by using JSON. stringify ( ) as shown in the example:

Читайте также:  Php value memory limit 2048m

Stringify a JavaScript Object

Mention below example will show how to convert a JavaScript object to JSON string:

// Sample JS object var obj = ; // Converting JS object to JSON string var json = JSON.stringify(obj); alert(json);

The output result of above example will show as:

Stringify a JavaScript Array

Mention below example will show how to convert a JavaScript array to JSON strings:

// Sample JS array var arr = ["Apple", "Banana", "Mango", "Orange", "Papaya"]; // Converting JS array to JSON string var json = JSON.stringify(arr); alert(json);

The output result of above example will show as:

["Apple","Banana","Mango","Orange","Papaya"]

Источник

JSON

The JSON namespace object contains static methods for parsing values from and converting values to JavaScript Object Notation (JSON).

Description

Unlike most global objects, JSON is not a constructor. You cannot use it with the new operator or invoke the JSON object as a function. All properties and methods of JSON are static (just like the Math object).

JavaScript and JSON differences

JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and null . It is based upon JavaScript syntax, but is distinct from JavaScript: most of JavaScript is not JSON. For example:

Property names must be double-quoted strings; trailing commas are forbidden.

Leading zeros are prohibited. A decimal point must be followed by at least one digit. NaN and Infinity are unsupported.

Any JSON text is a valid JavaScript expression, but only after the JSON superset revision. Before the revision, U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed in string literals and property keys in JSON; but the same use in JavaScript string literals is a SyntaxError .

Other differences include allowing only double-quoted strings and no support for undefined or comments. For those who wish to use a more human-friendly configuration format based on JSON, there is JSON5, used by the Babel compiler, and the more commonly used YAML.

The same text may represent different values in JavaScript object literals vs. JSON as well. For more information, see Object literal syntax vs. JSON.

Full JSON grammar

Valid JSON syntax is formally defined by the following grammar, expressed in ABNF, and copied from IETF JSON standard (RFC):

JSON-text = object / array begin-array = ws %x5B ws ; [ left square bracket begin-object = ws %x7B ws ; < left curly bracket end-array = ws %x5D ws ; ] right square bracket end-object = ws %x7D ws ; >right curly bracket name-separator = ws %x3A ws ; : colon value-separator = ws %x2C ws ; , comma ws = *( %x20 / ; Space %x09 / ; Horizontal tab %x0A / ; Line feed or New line %x0D ; Carriage return ) value = false / null / true / object / array / number / string false = %x66.61.6c.73.65 ; false null = %x6e.75.6c.6c ; null true = %x74.72.75.65 ; true object = begin-object [ member *( value-separator member ) ] end-object member = string name-separator value array = begin-array [ value *( value-separator value ) ] end-array number = [ minus ] int [ frac ] [ exp ] decimal-point = %x2E ; . digit1-9 = %x31-39 ; 1-9 e = %x65 / %x45 ; e E exp = e [ minus / plus ] 1*DIGIT frac = decimal-point 1*DIGIT int = zero / ( digit1-9 *DIGIT ) minus = %x2D ; - plus = %x2B ; + zero = %x30 ; 0 string = quotation-mark *char quotation-mark char = unescaped / escape ( %x22 / ; " quotation mark U+0022 %x5C / ; \ reverse solidus U+005C %x2F / ; / solidus U+002F %x62 / ; b backspace U+0008 %x66 / ; f form feed U+000C %x6E / ; n line feed U+000A %x72 / ; r carriage return U+000D %x74 / ; t tab U+0009 %x75 4HEXDIG ) ; uXXXX U+XXXX escape = %x5C ; \ quotation-mark = %x22 ; " unescaped = %x20-21 / %x23-5B / %x5D-10FFFF HEXDIG = DIGIT / %x41-46 / %x61-66 ; 0-9, A-F, or a-f ; HEXDIG equivalent to HEXDIG rule in [RFC5234] DIGIT = %x30-39 ; 0-9 ; DIGIT equivalent to DIGIT rule in [RFC5234]

Insignificant whitespace may be present anywhere except within a JSONNumber (numbers must contain no whitespace) or JSONString (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character (U+0009), carriage return (U+000D), line feed (U+000A), and space (U+0020) characters are the only valid whitespace characters.

Static properties

The initial value of the @@toStringTag property is the string «JSON» . This property is used in Object.prototype.toString() .

Static methods

Parse a piece of string text as JSON, optionally transforming the produced value and its properties, and return the value.

Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.

Examples

Example JSON

 "browsers":  "firefox":  "name": "Firefox", "pref_url": "about:config", "releases":  "1":  "release_date": "2004-11-09", "status": "retired", "engine": "Gecko", "engine_version": "1.7" > > > > > 

You can use the JSON.parse() method to convert the above JSON string into a JavaScript object:

const jsonText = ` < "browsers": < "firefox": < "name": "Firefox", "pref_url": "about:config", "releases": < "1": < "release_date": "2004-11-09", "status": "retired", "engine": "Gecko", "engine_version": "1.7" >> > > >`; console.log(JSON.parse(jsonText)); 

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 Jul 24, 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.

Источник

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