JavaScript Tutorial
JS - Introduction JS - Basic JS - Placement JS - Output JS - Statements JS - Syntax JS - Variables JS - Comments JS - Data Types JS - Operators JS - Operator Precedence JS - Condition JS - Switch JS - Functions JS - Objects JS - Loops For JS - Loops While JS - Break JS - Strings JS - String Methods JS - Numbers JS - Number Methods JS - Arrays JS - Array Methods JS - Array Iteration JS - Events JS - Event Listener JS - Event Propagation JS - Date JS - Math JS - Random JS - Boolean JS - Type Conversion JS - RegExp JS - Exception JS - Scope JS - Debugging JS - Hoisting JS - Strict Mode JS - this Keyword JS - Mistakes JS - Best Practices JS - Performance JS - Form Validation JS - ES6 Features
JS Objects
Object Definitions Object Properties Object Methods Object Constructors Object Prototypes
JS Functions
Function Definitions Function Parameters Function Call Function Apply Function Closures
JS HTML DOM
DOM Introduction DOM Methods DOM Selectors DOM HTML DOM CSS DOM Attributes DOM Navigation
JS Browser BOM
JS - Window JS - Screen JS - Location JS - History JS - Navigator JS - Popup Alert JS - Timing JS - Cookies
JS AJAX
AJAX - Introduction AJAX - XMLHttp AJAX - Request AJAX - Response AJAX - PHP
JS JSON
JSON - Introduction JSON - Syntax JSON - Data Types JSON - Parse JSON - Stringify JSON - Objects JSON - Arrays JSON - PHP JSON - JSONP
JS References
JavaScript Reference JavaScript Methods HTML DOM Reference

JSON.parse()

JSON is used to exchange data to/from a web server. When receiving data from a web server, the data is always a string.

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

Syntax:
JSON.parse(text, reviver)

The first parameter specifies the string to parse as JSON.

The optional second parameter specifies a function that checks each property, before returning the value.


Parsing JSON

Suppose we received the following text from a web server:

Using the JSON.parse() method we can convert JSON text into a JavaScript object:

Run code

JSON From the Server

You can request JSON from the server by using an AJAX request.

If the response from the server is written in JSON format, you can parse the string into a JavaScript object.

The following example requests the file demo.json and parse the response:

Run code

Array as JSON

Using the JSON.parse() method on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.

The following example requests the file json_array.txt and parse the response:

Run code

Parsing Dates

Date objects are not allowed in JSON.

If you need to include a date, write it as a string and convert it back into a date object later.

Run code

Note: Converting a string to a native object is called parsing, while converting a native object to a string so it can be transmitted across the network is called stringification.