Latest web development tutorials

JSON use

The JSON text is converted to JavaScript objects

One of the most common use of JSON, is read from the web server JSON data (as a file or as an HttpRequest), the JSON data into JavaScript objects, and then use that data in a Web page.

To make it easier for you to explain, we use string as input for presentation (rather than a file).


JSON instance - the object from the string

Create a JavaScript string containing the JSON syntax:

var txt = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

Since JSON syntax is a subset of JavaScript syntax, JavaScript eval () function can be used to convert the text to JSON JavaScript object.

eval () function uses JavaScript compiler can parse JSON text, and then generate JavaScript objects. The text must be enclosed in parentheses, so as to avoid syntax errors:

var obj = eval ("(" + txt + ")");

Using JavaScript objects in the page:

Examples

<p>
First Name: <span id="fname"></span><br />
Last Name: <span id="lname"></span><br />
</p>

<script>
document.getElementById("fname").innerHTML = obj.employees[1].firstName
document.getElementById("lname").innerHTML = obj.employees[1].lastName
</script>

try it"

JSON parser

lamp eval () function can compile and execute any JavaScript code. This hides a potential security issue.

Using JSON parser to convert JSON JavaScript object is a safer approach. JSON JSON text parser only recognizes, but does not compile the script.

In the browser, which provides native JSON support, JSON parsers and faster.

Newer browsers and the latest ECMAScript (JavaScript) standard contains native support for JSON is.

Web 浏览器支持 Web 软件支持
  • Firefox (Mozilla) 3.5
  • Internet Explorer 8
  • Chrome
  • Opera 10
  • Safari 4
  • jQuery
  • Yahoo UI
  • Prototype
  • Dojo
  • ECMAScript 1.5

try it"

For older browsers can use JavaScript libraries: https://github.com/douglascrockford/JSON-js

JSON format was originally developed originally specified by Douglas Crockford