JSON - Introduction
Online example
Through our editor, you can edit JavaScript code online and then view the result by clicking a button:
JSON example
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<title>Runoob Tutorial(runoob.com)
title
head
<
body
<
h2JavaScript creates a JSON object
h2
<
p
Site name:
<span id="jname" span>
<br/>Site URL:
<span id="jurl" span>
<br/>Site slogan:
<span id="jslogan" span>
<br/>p>
<script var JSONObject={"name">:
"
Runoob Tutorial
"
,
"
url
"
:
"
www.runoob.com
"
,
"
slogan
"
:
"
What you learn is not only technology, but also dreams!
"
}
;
document
.
getElementById
(
"
jname
"
)
.
innerHTML
=
JSONObject
.
name
document
.
getElementById
(
"
jurl
"
)
.
innerHTML
=
JSONObject
.
url
document
.
getElementById
(
"
jslogan
"
)
.
innerHTML
=
JSONObject
.
slogan
script
body
html
Try it »
Click the "Try it yourself" button to view the online example.
Similarities with XML
- JSON is plain text
- JSON is "self-describing" (human readable)
- JSON has a hierarchical structure (values within values)
- JSON can be parsed by JavaScript
- JSON data can be transmitted using AJAX
Differences from XML
- No end tags
- Shorter
- Faster to read and write
- Can be parsed using the built-in JavaScript eval() method
- Uses arrays
- Does not use reserved words
Why use JSON?
For AJAX applications, JSON is faster and easier to use than XML:
Using XML
- Read the XML document
- Use the XML DOM to loop through the document
- Read the values and store them in variables
Using JSON
- Read the JSON string
- Process the JSON string with eval()