JSON Usage
Converting JSON text to a JavaScript object
One of the most common uses of JSON is to read JSON data from a web server (as a file or as an HttpRequest), convert the JSON data into a JavaScript object, and then use that data in a web page.
To explain more simply, we use a string as the input for the demonstration (instead of a file).
JSON example - object from a string
Create a JavaScript string that contains JSON syntax:
var
txt
=
'
{ "sites" : [
'
'
{ "name":"Runoob Tutorial" , "url":"www.runoob.com" },
'
'
{ "name":"google" , "url":"www.google.com" },
'
'
{ "name":"weibo" , "url":"www.weibo.com" } ]}
'
;
Because JSON syntax is a subset of JavaScript syntax, the JavaScript function eval() can be used to convert JSON text into a JavaScript object.
The eval() function uses the JavaScript compiler to parse JSON text and then generate a JavaScript object. The text must be wrapped in parentheses to avoid syntax errors:
var obj = eval ("(" + txt + ")");
Using the JavaScript object in a web page:
Example
var
txt
=
'
{ "sites" : [
'
'
{ "name":"Runoob Tutorial" , "url":"www.runoob.com" },
'
'
{ "name":"google" , "url":"www.google.com" },
'
'
{ "name":"weibo" , "url":"www.weibo.com" } ]}
'
;
var
obj
=
eval
(
"
(
"
txt
"
)
"
)
;
document
.
getElementById
(
"
name
"
)
.
innerHTML
=
obj
.
sites
[
0
]
.
name
document
.
getElementById
(
"
url
"
)
.
innerHTML
=
obj
.
sites
[
0
]
.
url
Try it »
JSON parser
The eval() function can compile and execute any JavaScript code. This hides a potential security problem.
It is safer to use a JSON parser to convert JSON into a JavaScript object. A JSON parser only recognizes JSON text and does not compile scripts.
In browsers, this provides native JSON support, and the JSON parser is faster.
Newer browsers and the latest ECMAScript (JavaScript) standards both include native support for JSON.
| Web browser support | Web software support |
|---|---|
|
|
- jQuery
- Yahoo UI
- Prototype
- Dojo
- ECMAScript 1.5
For older browsers, you can use a JavaScript library: https://github.com/douglascrockford/JSON-js
The JSON format was originally originally specified by Douglas Crockford