JSON Usage
Convert 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 to a JavaScript object, and then use that data in a web page.
To explain it more simply, we use a string as input for demonstration (instead of a file).
JSON Example - Object from String
Create a JavaScript string containing JSON syntax:
Since JSON syntax is a subset of JavaScript syntax, the JavaScript function eval() can be used to convert JSON text to a JavaScript object.
The eval() function uses the JavaScript compiler, which can parse JSON text and then generate a JavaScript object. The text must be wrapped in parentheses to avoid syntax errors:
Use the JavaScript object in a web page:
Example
Try it yourself »
JSON Parser
The eval() function can compile and execute any JavaScript code. This hides a potential security issue.
Using a JSON parser to convert JSON to a JavaScript object is a safer practice. A JSON parser only recognizes JSON text and does not compile scripts.
In browsers, this provides native JSON support, and JSON parsers are faster.
Newer browsers and the latest ECMAScript (JavaScript) standard include native support for JSON.
| Web Browser Support | Web Software Support |
|---|---|
|
|
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
Other extensions