JSON usage
Convert JSON text to JavaScript object
One of the most common uses of JSON is to read JSON data from the web server (as a file or as an HttpRequest), and convert the JSON data into Convert to a JavaScript object and use the data in the web page.
To explain it more simply for you, we use strings as input for demonstration (instead of files).
JSON instance - object from string
Create a JavaScript string containing JSON syntax:
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
Since JSON syntax is a subset of JavaScript syntax, the JavaScript function eval() Can be used to convert JSON text into JavaScript objects.
The eval() function uses the JavaScript compiler to parse JSON text and then generate JavaScript objects. Text must be enclosed in brackets to avoid syntax errors:
On the web page Use JavaScript objects in:
Instance
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <h2>从 JSON 字符串中创建对象</h2> <p> 名: <span id="fname"></span><br> 姓: <span id="lname"></span><br> </p> <script> var txt = '{"employees":[' + '{"firstName":"John","lastName":"Doe" },' + '{"firstName":"Anna","lastName":"Smith" },' + '{"firstName":"Peter","lastName":"Jones" }]}'; var obj = eval ("(" + txt + ")"); document.getElementById("fname").innerHTML=obj.employees[1].firstName document.getElementById("lname").innerHTML=obj.employees[1].lastName </script> </body> </html>
Run Instance»
Click the "Run Instance" button to view Online Example
JSON Parser
The eval() function can compile and execute any JavaScript code. This hides a potential security issue.
It is safer to use a JSON parser to convert JSON to JavaScript objects. The JSON parser only understands JSON text and does not compile scripts.
In the browser, this provides native JSON support and a faster JSON parser.
Newer browsers and the latest ECMAScript (JavaScript) standard include native support for JSON.
Web browser support | Web software support |
---|---|
|
|