How To Parse JSON with JSON.parse() JavaScript Function? – POFTUT

How To Parse JSON with JSON.parse() JavaScript Function?

JSON is a very popular data format which is mainly used in web applications in order to transmit data in a common format. JSON is an ASCII or non-binary format which is human readable. JavaScript generally used to create, use, consume JSON type data. JSON.parse() is a function which is used to parse JSON structured data.

Example JSON Data

During the JSON parse tutorial, we will use the following example JSON data which contains different types like string, integer, date, array, etc.

Example JSON Data

Example JSON Data

JSON.parse() Function Syntax

parse() function is provided by JSON library in order to parse JSON data format. There are two parameters where one is optional.

  • text is the data the function will parse which is in JSON format.
  • reviver is optional parameters where If a function, this prescribes how the value originally produced by parsing is transformed, before being returned.

This function will return an Object corresponding to the given JSON text. If the format of the given text does not comply with the JSON format specification the SyntaxError exception will be thrown.

Parse JSON

We can parse simply provided JSON data with the JSON.parse() function. We will provide the data which is held by the variable named person like below. In this example, we will print parsed variables named firstName, lastName, age.

Parse JSON

Parse JSON

Parse JSON Array

We can also parse a JSON array with the parse() function. In this example, we will use an array named names. We will parse the names array and use in JavaScript.

Parse JSON Array

Parse JSON Array

Parse Date Data with JSON

The date is the special type where we have to use it especially by creating reviver function which will handle data values with Date type in JavaScript programming language. We will create a function which will handle the birth key specially and convert the JSON date data in JavaScript Date type or format like below.

Parse Date Data with JSON

Parse Date Data with JSON

Parse Function with JSON

As JavaScript is an interpreted language we can create and run functions is different ways. We can also represent functions in JSON data and run these functions after parsing them. In this example, we will store the function with the key value hello and run after parsing it.

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)