Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JSON parse

A typical use of JSON is for exchanging data with a web server. When data is received from a web server, it is always in string format. By using JSON.parse(), the string is converted into a JavaScript object.

Example – Parsing JSON

Imagine we received the following text from a web server:

‘{“name”:”John”, “age”:30, “city”:”New York”}’

Use the JavaScript function JSON.parse() to transform the text into a JavaScript object:

const obj = JSON.parse(‘{“name”:”John”, “age”:30, “city”:”New York”}’);
Ensure the text is in valid JSON format, otherwise, a syntax error will occur.

Use the JavaScript object within your page:

Example

<p id=”demo”></p>

<script>
document.getElementById(“demo”).innerHTML = obj.name;
</script>

Array as JSON

When using JSON.parse() on JSON derived from an array, the method will return a JavaScript array rather than a JavaScript object.

Example

const text = ‘[“Ford”, “BMW”, “Audi”, “Fiat”]’;
const myArr = JSON.parse(text);

Exceptions

Parsing Dates

Date objects are not supported in JSON.

If you need to include a date, represent it as a string.

You can later convert it back into a date object.

Example

Transform a string into a date:

const text = ‘{“name”:”John”, “birth”:”1986-12-14″, “city”:”New York”}’;
const obj = JSON.parse(text);
obj.birth = new Date(obj.birth);

document.getElementById(“demo”).innerHTML = obj.name + “, “ + obj.birth;

Alternatively, you can use the second parameter of the JSON.parse() function, known as the reviver.

The reviver is a function that examines each property before returning its value.

Example

Use the reviver function to convert a string into a date:

const text = ‘{“name”:”John”, “birth”:”1986-12-14″, “city”:”New York”}’;
const obj = JSON.parse(text, function (key, value) {
  if (key == “birth”) {
    return new Date(value);
  } else {
    return value;
  }
});

document.getElementById(“demo”).innerHTML = obj.name + “, “ + obj.birth;

Parsing Functions

Functions are not permitted in JSON.

If you need to include a function, represent it as a string.

You can later convert it back into a function.

Example

Transform a string into a function:

const text = ‘{“name”:”John”, “age”:”function () {return 30;}”, “city”:”New York”}’;
const obj = JSON.parse(text);
obj.age = eval(“(“ + obj.age + “)”);

document.getElementById(“demo”).innerHTML = obj.name + “, “ + obj.age();
It is best to avoid using functions in JSON, as they will lose their scope, and you would need to use eval() to convert them back into functions.