Download as pdf or txt
Download as pdf or txt
You are on page 1of 56

2/14/2018 JSON Introduction

w3schools.com
THE WORLD'S LARGEST WEB DEVELOPER SITE

  HTML CSS JAVASCRIPT MORE   

JSON - Introduction
❮ Previous Next ❯

JSON: JavaScript Object Notation.

JSON is a syntax for storing and exchanging data.

JSON is text, written with JavaScript object notation.

Exchanging Data
When exchanging data between a browser and a server, the data can only be text.

JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.

We can also convert any JSON received from the server into JavaScript objects.

https://www.w3schools.com/js/js_json_intro.asp 1/6
2/14/2018 JSON Introduction

This way we can work with the data as JavaScript objects, with no complicated parsing and translations.

Sending Data
If you have data stored in a JavaScript object, you can convert the object into JSON, and send it to a server:

Example

var myObj = { "name":"John", "age":31, "city":"New York" };


var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;

Try it Yourself »

You will learn more about the JSON.stringify() function later in this tutorial.

Receiving Data
If you receive data in JSON format, you can convert it into a JavaScript object:

Example

var myJSON = '{ "name":"John", "age":31, "city":"New York" }';


var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;

https://www.w3schools.com/js/js_json_intro.asp 2/6
2/14/2018 JSON Introduction

Try it Yourself »

You will learn more about the JSON.parse() function later in this tutorial.

Storing Data
When storing data, the data has to be a certain format, and regardless of where you choose to store it, text is always one of
the legal formats.

JSON makes it possible to store JavaScript objects as text.

Example
Storing data in local storage

//Storing data:
myObj = { "name":"John", "age":31, "city":"New York" };
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);

//Retrieving data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;

https://www.w3schools.com/js/js_json_intro.asp 3/6
2/14/2018 JSON Introduction

Try it Yourself »

What is JSON?
JSON stands for JavaScript Object Notation
JSON is a lightweight data-interchange format
JSON is "self-describing" and easy to understand
JSON is language independent *

*
JSON uses JavaScript syntax, but the JSON format is text only.
Text can be read and used as a data format by any programming language.

The JSON format was originally specified by Douglas Crockford.

Why use JSON?


Since the JSON format is text only, it can easily be sent to and from a server, and used as a data format by any
programming language.

JavaScript has a built in function to convert a string, written in JSON format, into native JavaScript objects:

JSON.parse()

So, if you receive data from a server, in JSON format, you can use it like any other JavaScript object.

❮ Previous Next ❯

https://www.w3schools.com/js/js_json_intro.asp 4/6
2/14/2018 JSON Introduction

COLOR PICKER

HOW TO
Tabs
Dropdowns
Accordions
Convert Weights
Animated Buttons
Side Navigation
Top Navigation
Modal Boxes
Progress Bars
Parallax
Login Form
HTML Includes
Google Maps
Range Sliders
Tooltips
Slideshow
Filter List
Sort List

https://www.w3schools.com/js/js_json_intro.asp 5/6
2/14/2018 JSON Introduction

SHARE

  

CERTIFICATES
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML.

Read More »

REPORT ERROR PRINT PAGE FORUM ABOUT

Top 10 Tutorials Top 10 References


HTML Tutorial HTML Reference
CSS Tutorial CSS Reference
JavaScript Tutorial JavaScript Reference
W3.CSS Tutorial W3.CSS Reference
Bootstrap Tutorial Bootstrap Reference
SQL Tutorial Browser Statistics
PHP Tutorial PHP Reference
jQuery Tutorial HTML Colors
Angular Tutorial jQuery Reference
How To Tutorial AngularJS Reference

https://www.w3schools.com/js/js_json_intro.asp 6/6
2/14/2018 JSON Syntax

w3schools.com
THE WORLD'S LARGEST WEB DEVELOPER SITE

  HTML CSS JAVASCRIPT MORE   

JSON Syntax
❮ Previous Next ❯

The JSON syntax is a subset of the JavaScript syntax.

JSON Syntax Rules


JSON syntax is derived from JavaScript object notation syntax:

Data is in name/value pairs


Data is separated by commas
Curly braces hold objects
Square brackets hold arrays

https://www.w3schools.com/js/js_json_syntax.asp 1/7
2/14/2018 JSON Syntax

JSON Data - A Name and a Value


JSON data is written as name/value pairs.

A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

Example

"name":"John"

JSON names require double quotes. JavaScript names don't.

JSON - Evaluates to JavaScript Objects


The JSON format is almost identical to JavaScript objects.

In JSON, keys must be strings, written with double quotes:

JSON

{ "name":"John" }

In JavaScript, keys can be strings, numbers, or identifier names:

JavaScript
https://www.w3schools.com/js/js_json_syntax.asp 2/7
2/14/2018 JSON Syntax

{ name:"John" }

JSON Values
In JSON, values must be one of the following data types:

a string
a number
an object (JSON object)
an array
a boolean
null

In JavaScript values can be all of the above, plus any other valid JavaScript expression, including:

a function
a date
undefined

In JSON, string values must be written with double quotes:

JSON

{ "name":"John" }

In JavaScript, you can write string values with double or single quotes:

https://www.w3schools.com/js/js_json_syntax.asp 3/7
2/14/2018 JSON Syntax

JavaScript

{ name:'John' }

JSON Uses JavaScript Syntax


Because JSON syntax is derived from JavaScript object notation, very little extra software is needed to work with JSON
within JavaScript.

With JavaScript you can create an object and assign data to it, like this:

Example

var person = { "name":"John", "age":31, "city":"New York" };

You can access a JavaScript object like this:

Example

// returns John
person.name;

Try it Yourself »

It can also be accessed like this:


https://www.w3schools.com/js/js_json_syntax.asp 4/7
2/14/2018 JSON Syntax

Example

// returns John
person["name"];

Try it Yourself »

Data can be modified like this:

Example

person.name = "Gilbert";

Try it Yourself »

It can also be modified like this:

Example

person["name"] = "Gilbert";

Try it Yourself »

You will learn how to convert JavaScript objects into JSON later in this tutorial.

https://www.w3schools.com/js/js_json_syntax.asp 5/7
2/14/2018 JSON Syntax

JavaScript Arrays as JSON


The same way JavaScript objects can be used as JSON, JavaScript arrays can also be used as JSON.

You will learn more about arrays as JSON later in this tutorial.

JSON Files
The file type for JSON files is ".json"
The MIME type for JSON text is "application/json"

❮ Previous Next ❯

COLOR PICKER

HOW TO
Tabs
Dropdowns
Accordions

https://www.w3schools.com/js/js_json_syntax.asp 6/7
2/14/2018 JSON Syntax

Convert Weights
Animated Buttons
Side Navigation
Top Navigation
Modal Boxes
Progress Bars
Parallax
Login Form
HTML Includes
Google Maps
Range Sliders
Tooltips
Slideshow
Filter List
Sort List

SHARE

  

CERTIFICATES
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML.

Read More »

https://www.w3schools.com/js/js_json_syntax.asp 7/7
2/14/2018 JSON vs XML

w3schools.com
THE WORLD'S LARGEST WEB DEVELOPER SITE

  HTML CSS JAVASCRIPT MORE   

JSON vs XML
❮ Previous Next ❯

Both JSON and XML can be used to receive data from a web server.

The following JSON and XML examples both defines an employees object, with an array of 3 employees:

JSON Example

{"employees":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}

https://www.w3schools.com/js/js_json_xml.asp 1/4
2/14/2018 JSON vs XML

XML Example

<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>

 JSON is Like XML Because


Both JSON and XML are "self describing" (human readable)
Both JSON and XML are hierarchical (values within values)
Both JSON and XML can be parsed and used by lots of programming languages
Both JSON and XML can be fetched with an XMLHttpRequest

JSON is Unlike XML Because


JSON doesn't use end tag
JSON is shorter
JSON is quicker to read and write
JSON can use arrays
https://www.w3schools.com/js/js_json_xml.asp 2/4
2/14/2018 JSON vs XML

The biggest difference is:

XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function.

Why JSON is Better Than XML


XML is much more difficult to parse than JSON.
JSON is parsed into a ready-to-use JavaScript object.

For AJAX applications, JSON is faster and easier than XML:

Using XML

Fetch an XML document


Use the XML DOM to loop through the document
Extract values and store in variables

Using JSON

Fetch a JSON string


JSON.Parse the JSON string

❮ Previous Next ❯

COLOR PICKER

https://www.w3schools.com/js/js_json_xml.asp 3/4
2/14/2018 JSON vs XML

HOW TO
Tabs
Dropdowns
Accordions
Convert Weights
Animated Buttons
Side Navigation
Top Navigation
Modal Boxes
Progress Bars
Parallax
Login Form
HTML Includes
Google Maps
Range Sliders
Tooltips
Slideshow
Filter List
Sort List

SHARE

  

https://www.w3schools.com/js/js_json_xml.asp 4/4
2/14/2018 JSON Data Types

w3schools.com
THE WORLD'S LARGEST WEB DEVELOPER SITE

  HTML CSS JAVASCRIPT MORE   

JSON Data Types


❮ Previous Next ❯

Valid Data Types


In JSON, values must be one of the following data types:

a string
a number
an object (JSON object)
an array
a boolean
null

JSON values cannot be one of the following data types:

a function

https://www.w3schools.com/js/js_json_datatypes.asp 1/5
2/14/2018 JSON Data Types

a date
undefined

JSON Strings
Strings in JSON must be written in double quotes.

Example

{ "name":"John" }

JSON Numbers
Numbers in JSON must be an integer or a floating point.

Example

{ "age":30 }

JSON Objects
Values in JSON can be objects.

https://www.w3schools.com/js/js_json_datatypes.asp 2/5
2/14/2018 JSON Data Types

Example

{
"employee":{ "name":"John", "age":30, "city":"New York" }
}

Objects as values in JSON must follow the same rules as JSON objects.

JSON Arrays
Values in JSON can be arrays.

Example

{
"employees":[ "John", "Anna", "Peter" ]
}

JSON Booleans
https://www.w3schools.com/js/js_json_datatypes.asp 3/5
2/14/2018 JSON Data Types

Values in JSON can be true/false.

Example

{ "sale":true }

JSON null
Values in JSON can be null.

Example

{ "middlename":null }

❮ Previous Next ❯

COLOR PICKER

https://www.w3schools.com/js/js_json_datatypes.asp 4/5
2/14/2018 JSON Data Types

HOW TO
Tabs
Dropdowns
Accordions
Convert Weights
Animated Buttons
Side Navigation
Top Navigation
Modal Boxes
Progress Bars
Parallax
Login Form
HTML Includes
Google Maps
Range Sliders
Tooltips
Slideshow
Filter List
Sort List

SHARE

  

CERTIFICATES
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML.

https://www.w3schools.com/js/js_json_datatypes.asp 5/5
2/14/2018 JSON Objects

w3schools.com
THE WORLD'S LARGEST WEB DEVELOPER SITE

  HTML CSS JAVASCRIPT MORE   

JSON Objects
❮ Previous Next ❯

Object Syntax

Example

{ "name":"John", "age":30, "car":null }

JSON objects are surrounded by curly braces {}.

JSON objects are written in key/value pairs.

Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null).

https://www.w3schools.com/js/js_json_objects.asp 1/7
2/14/2018 JSON Objects

Keys and values are separated by a colon.

Each key/value pair is separated by a comma.

Accessing Object Values


You can access the object values by using dot (.) notation:

Example

myObj = { "name":"John", "age":30, "car":null };


x = myObj.name;

Try it Yourself »

You can also access the object values by using bracket ([]) notation:

Example

myObj = { "name":"John", "age":30, "car":null };


x = myObj["name"];

Try it Yourself »

https://www.w3schools.com/js/js_json_objects.asp 2/7
2/14/2018 JSON Objects

Looping an Object
You can loop through object properties by using the for-in loop:

Example

myObj = { "name":"John", "age":30, "car":null };


for (x in myObj) {
document.getElementById("demo").innerHTML += x;
}

Try it Yourself »

In a for-in loop, use the bracket notation to access the property values:

Example

myObj = { "name":"John", "age":30, "car":null };


for (x in myObj) {
document.getElementById("demo").innerHTML += myObj[x];
}

Try it Yourself »

https://www.w3schools.com/js/js_json_objects.asp 3/7
2/14/2018 JSON Objects

Nested JSON Objects


Values in a JSON object can be another JSON object.

Example

myObj = {
"name":"John",
"age":30,
"cars": {
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
}
}

You can access nested JSON objects by using the dot notation or bracket notation:

Example

x = myObj.cars.car2;
//or:
x = myObj.cars["car2"];

Try it Yourself »

https://www.w3schools.com/js/js_json_objects.asp 4/7
2/14/2018 JSON Objects

Modify Values
You can use the dot notation to modify any value in a JSON object:

Example

myObj.cars.car2 = "Mercedes";

Try it Yourself »

You can also use the bracket notation to modify a value in a JSON object:

Example

myObj.cars["car2"] = "Mercedes";

Try it Yourself »

Delete Object Properties


Use the delete keyword to delete properties from a JSON object:

Example

https://www.w3schools.com/js/js_json_objects.asp 5/7
2/14/2018 JSON Objects

delete myObj.cars.car2;

Try it Yourself »

❮ Previous Next ❯

COLOR PICKER

HOW TO
Tabs
Dropdowns
Accordions
Convert Weights
Animated Buttons
Side Navigation
Top Navigation
Modal Boxes
Progress Bars
Parallax

https://www.w3schools.com/js/js_json_objects.asp 6/7
2/14/2018 JSON Objects

Login Form
HTML Includes
Google Maps
Range Sliders
Tooltips
Slideshow
Filter List
Sort List

SHARE

  

CERTIFICATES
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML.

Read More »

REPORT ERROR PRINT PAGE FORUM ABOUT

Top 10 Tutorials Top 10 References


https://www.w3schools.com/js/js_json_objects.asp 7/7
2/14/2018 JSON Arrays

w3schools.com
THE WORLD'S LARGEST WEB DEVELOPER SITE

  HTML CSS JAVASCRIPT MORE   

JSON Arrays
❮ Previous Next ❯

Arrays as JSON Objects

Example

[ "Ford", "BMW", "Fiat" ]

Arrays in JSON are almost the same as arrays in JavaScript.

In JSON, array values must be of type string, number, object, array, boolean or null.

In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates,
and undefined.

https://www.w3schools.com/js/js_json_arrays.asp 1/6
2/14/2018 JSON Arrays

Arrays in JSON Objects


Arrays can be values of an object property:

Example

{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}

Accessing Array Values


You access the array values by using the index number:

Example

x = myObj.cars[0];

Try it Yourself »

Looping Through an Array


https://www.w3schools.com/js/js_json_arrays.asp 2/6
2/14/2018 JSON Arrays

You can access array values by using a for-in loop:

Example

for (i in myObj.cars) {
x += myObj.cars[i];
}

Try it Yourself »

Or you can use a for loop:

Example

for (i = 0; i < myObj.cars.length; i++) {


x += myObj.cars[i];
}

Try it Yourself »

Nested Arrays in JSON Objects


Values in an array can also be another array, or even another JSON object:
https://www.w3schools.com/js/js_json_arrays.asp 3/6
2/14/2018 JSON Arrays

Example

myObj = {
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}

To access arrays inside arrays, use a for-in loop for each array:

Example

for (i in myObj.cars) {
x += "<h1>" + myObj.cars[i].name + "</h1>";
for (j in myObj.cars[i].models) {
x += myObj.cars[i].models[j];
}
}

Try it Yourself »

https://www.w3schools.com/js/js_json_arrays.asp 4/6
2/14/2018 JSON Arrays

Modify Array Values


Use the index number to modify an array:

Example

myObj.cars[1] = "Mercedes";

Try it Yourself »

Delete Array Items


Use the delete keyword to delete items from an array:

Example

delete myObj.cars[1];

Try it Yourself »

❮ Previous Next ❯

https://www.w3schools.com/js/js_json_arrays.asp 5/6
2/14/2018 JSON Arrays

COLOR PICKER

HOW TO
Tabs
Dropdowns
Accordions
Convert Weights
Animated Buttons
Side Navigation
Top Navigation
Modal Boxes
Progress Bars
Parallax
Login Form
HTML Includes
Google Maps
Range Sliders
Tooltips
Slideshow
Filter List
Sort List

SHARE

https://www.w3schools.com/js/js_json_arrays.asp 6/6
2/14/2018 JSON.parse()

w3schools.com
THE WORLD'S LARGEST WEB DEVELOPER SITE

  HTML CSS JAVASCRIPT MORE   

JSON.parse()
❮ Previous Next ❯

A common use of JSON is to exchange data to/from a web server.

When receiving data from a web server, the data is always a string.

Parse the data with JSON.parse(), and the data becomes a JavaScript object.

Example - Parsing JSON


Imagine we received this text from a web server:

'{ "name":"John", "age":30, "city":"New York"}'

https://www.w3schools.com/js/js_json_parse.asp 1/8
2/14/2018 JSON.parse()

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

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

Make sure the text is written in JSON format, or else you will get a syntax error.

Use the JavaScript object in your page:

Example

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
</script>

Try it Yourself »

JSON From the Server


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

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

Example
https://www.w3schools.com/js/js_json_parse.asp 2/8
2/14/2018 JSON.parse()

Use the XMLHttpRequest to get data from the server:

var xmlhttp = new XMLHttpRequest();


xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();

Try it Yourself »

Take a look at json_demo.txt

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

Example
The JSON returned from the server is an array:

https://www.w3schools.com/js/js_json_parse.asp 3/8
2/14/2018 JSON.parse()

var xmlhttp = new XMLHttpRequest();


xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myArr[0];
}
};
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();

Try it Yourself »

Take a look at json_demo_array.txt

Exceptions
Parsing Dates
Date objects are not allowed in JSON.

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

You can convert it back into a date object later:

Example
Convert a string into a date:

https://www.w3schools.com/js/js_json_parse.asp 4/8
2/14/2018 JSON.parse()

var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';


var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);

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

Try it Yourself »

Or, you can use the second parameter, of the JSON.parse() function, called reviver.

The reviver parameter is a function that checks each property, before returning the value.

Example
Convert a string into a date, using the reviver function:

var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';


var 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;

Try it Yourself »

https://www.w3schools.com/js/js_json_parse.asp 5/8
2/14/2018 JSON.parse()

Parsing Functions
Functions are not allowed in JSON.

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

You can convert it back into a function later:

Example
Convert a string into a function:

var text = '{ "name":"John", "age":"function () {return 30;}", "city":"New York"}';


var obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");

document.getElementById("demo").innerHTML = obj.name + ", " + obj.age();

Try it Yourself »

You should avoid using functions in JSON, the functions will lose their scope, and you would have to use eval() to
convert them back into functions.

Browser Support
The JSON.parse() function is included in all major browsers and in the latest ECMAScript (JavaScript) standard:

https://www.w3schools.com/js/js_json_parse.asp 6/8
2/14/2018 JSON.parse()

Web Browsers Support

Firefox 3.5
Internet Explorer 8
Chrome
Opera 10
Safari 4

For older browsers, a JavaScript library is available at https://github.com/douglascrockford/JSON-js.

❮ Previous Next ❯

COLOR PICKER

HOW TO
Tabs
Dropdowns
Accordions
Convert Weights
https://www.w3schools.com/js/js_json_parse.asp 7/8
2/14/2018 JSON.parse()

Animated Buttons
Side Navigation
Top Navigation
Modal Boxes
Progress Bars
Parallax
Login Form
HTML Includes
Google Maps
Range Sliders
Tooltips
Slideshow
Filter List
Sort List

SHARE

  

CERTIFICATES
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML.

Read More »

https://www.w3schools.com/js/js_json_parse.asp 8/8
2/14/2018 JSON.stringify()

w3schools.com
THE WORLD'S LARGEST WEB DEVELOPER SITE

  HTML CSS JAVASCRIPT MORE   

JSON.stringify()
❮ Previous Next ❯

A common use of JSON is to exchange data to/from a web server.

When sending data to a web server, the data has to be a string.

Convert a JavaScript object into a string with JSON.stringify().

Stringify a JavaScript Object


Imagine we have this object in JavaScript:

var obj = { "name":"John", "age":30, "city":"New York"};

https://www.w3schools.com/js/js_json_stringify.asp 1/7
2/14/2018 JSON.stringify()

Use the JavaScript function JSON.stringify() to convert it into a string.

var myJSON = JSON.stringify(obj);

The result will be a string following the JSON notation.

myJSON is now a string, and ready to be sent to a server:

Example

var obj = { "name":"John", "age":30, "city":"New York"};


var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

Try it Yourself »

You will learn how to send JSON to the server in the next chapter.

Stringify a JavaScript Array


It is also possible to stringify JavaScript arrays:

Imagine we have this array in JavaScript:

var arr = [ "John", "Peter", "Sally", "Jane" ];


https://www.w3schools.com/js/js_json_stringify.asp 2/7
2/14/2018 JSON.stringify()

Use the JavaScript function JSON.stringify() to convert it into a string.

var myJSON = JSON.stringify(arr);

The result will be a string following the JSON notation.

myJSON is now a string, and ready to be sent to a server:

Example

var arr = [ "John", "Peter", "Sally", "Jane" ];


var myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myJSON;

Try it Yourself »

You will learn how to send JSON to the server in the next chapter.

Exceptions

https://www.w3schools.com/js/js_json_stringify.asp 3/7
2/14/2018 JSON.stringify()

Stringify Dates
In JSON, date objects are not allowed. The JSON.stringify() function will convert any dates into strings.

Example

var obj = { "name":"John", "today":new Date(), "city":"New York"};


var myJSON = JSON.stringify(obj);

document.getElementById("demo").innerHTML = myJSON;

Try it Yourself »

You can convert the string back into a date object at the receiver.

Stringify Functions
In JSON, functions are not allowed as object values.

The JSON.stringify() function will remove any functions from a JavaScript object, both the key and the value:

Example

var obj = { "name":"John", "age":function () {return 30;}, "city":"New York"};


var myJSON = JSON.stringify(obj);

document.getElementById("demo").innerHTML = myJSON;

https://www.w3schools.com/js/js_json_stringify.asp 4/7
2/14/2018 JSON.stringify()

Try it Yourself »

This can be omitted if you convert your functions into strings before running the JSON.stringify() function.

Example

var obj = { "name":"John", "age":function () {return 30;}, "city":"New York"};


obj.age = obj.age.toString();
var myJSON = JSON.stringify(obj);

document.getElementById("demo").innerHTML = myJSON;

Try it Yourself »

You should avoid using functions in JSON, the functions will lose their scope, and you would have to use eval() to
convert them back into functions.

Browser Support
The JSON.stringify() function is included in all major browsers and in the latest ECMAScript (JavaScript) standard:

Web Browsers Support

Firefox 3.5
Internet Explorer 8

https://www.w3schools.com/js/js_json_stringify.asp 5/7
2/14/2018 JSON.stringify()

Chrome
Opera 10
Safari 4

❮ Previous Next ❯

COLOR PICKER

HOW TO
Tabs
Dropdowns
Accordions
Convert Weights
Animated Buttons
Side Navigation
Top Navigation
Modal Boxes
Progress Bars
Parallax

https://www.w3schools.com/js/js_json_stringify.asp 6/7
2/14/2018 JSON.stringify()

Login Form
HTML Includes
Google Maps
Range Sliders
Tooltips
Slideshow
Filter List
Sort List

SHARE

  

CERTIFICATES
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML.

Read More »

REPORT ERROR PRINT PAGE FORUM ABOUT

Top 10 Tutorials Top 10 References


https://www.w3schools.com/js/js_json_stringify.asp 7/7
2/14/2018 JSON HTML

w3schools.com
THE WORLD'S LARGEST WEB DEVELOPER SITE

  HTML CSS JAVASCRIPT MORE   

JSON HTML
❮ Previous Next ❯

JSON can very easily be translated into JavaScript.

JavaScript can be used to make HTML in your web pages.

HTML Table
Make an HTML table with data received as JSON:

Example

obj = { "table":"customers", "limit":20 };


dbParam = JSON.stringify(obj);
https://www.w3schools.com/js/js_json_html.asp 1/6
2/14/2018 JSON HTML

xmlhttp = new XMLHttpRequest();


xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table border='1'>"
for (x in myObj) {
txt += "<tr><td>" + myObj[x].name + "</td></tr>";
}
txt += "</table>"
document.getElementById("demo").innerHTML = txt;
}
}
xmlhttp.open("POST", "json_demo_db_post.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

Try it Yourself »

Dynamic HTML Table


Make the HTML table based on the value of a drop down menu: Choose an option:

Example

<select id="myselect" onchange="change_myselect(this.value)">


<option value="">Choose an option:</option>
<option value="customers">Customers</option>

https://www.w3schools.com/js/js_json_html.asp 2/6
2/14/2018 JSON HTML

<option value="products">Products</option>
<option value="suppliers">Suppliers</option>
</select>

<script>
function change_myselect(sel) {
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { "table":sel, "limit":20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table border='1'>"
for (x in myObj) {
txt += "<tr><td>" + myObj[x].name + "</td></tr>";
}
txt += "</table>"
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("POST", "json_demo_db_post.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
}
</script>

Try it Yourself »

https://www.w3schools.com/js/js_json_html.asp 3/6
2/14/2018 JSON HTML

HTML Drop Down List


Make an HTML drop down list with data received as JSON:

Example

obj = { "table":"customers", "limit":20 };


dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<select>"
for (x in myObj) {
txt += "<option>" + myObj[x].name;
}
txt += "</select>"
document.getElementById("demo").innerHTML = txt;
}
}
xmlhttp.open("POST", "json_demo_db_post.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

Try it Yourself »

https://www.w3schools.com/js/js_json_html.asp 4/6
2/14/2018 JSON HTML

❮ Previous Next ❯

COLOR PICKER

HOW TO
Tabs
Dropdowns
Accordions
Convert Weights
Animated Buttons
Side Navigation
Top Navigation
Modal Boxes
Progress Bars
Parallax
Login Form
HTML Includes
Google Maps
Range Sliders
Tooltips
Slideshow

https://www.w3schools.com/js/js_json_html.asp 5/6
2/14/2018 JSON HTML

Filter List
Sort List

SHARE

  

CERTIFICATES
HTML, CSS, JavaScript, PHP, jQuery, Bootstrap and XML.

Read More »

REPORT ERROR PRINT PAGE FORUM ABOUT

Top 10 Tutorials Top 10 References


HTML Tutorial HTML Reference
CSS Tutorial CSS Reference
JavaScript Tutorial JavaScript Reference
W3.CSS Tutorial W3.CSS Reference
Bootstrap Tutorial Bootstrap Reference
SQL Tutorial Browser Statistics
PHP Tutorial PHP Reference

https://www.w3schools.com/js/js_json_html.asp 6/6

You might also like