3.JSON use

The JSON text into a JavaScript object

One of the most common use of JSON, read JSON data from the web server (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 demonstrate the use of strings (instead of the file) as input.


Examples JSON - string objects from

Create a JavaScript string containing the JSON syntax:

var txt = '{ "sites" : [' + '{ "name":"菜鸟教程" , "url":"www.runoob.com" },' + '{ "name":"google" , "url":"www.google.com" },' + '{ "name":"微博" , "url":"www.weibo.com" } ]}';

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

eval () function using the JavaScript compiler, JSON text may be parsed, and then generates a JavaScript object. The text must be enclosed in parentheses, so as to avoid syntax errors:

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

The use of JavaScript objects in the page:

Examples

var txt = '{ "sites" : [' + '{ "name":"菜鸟教程" , "url":"www.runoob.com" },' + '{ "name":"google" , "url":"www.google.com" },' + '{ "name":"微博" , "url":"www.weibo.com" } ]}'; var obj = eval ("(" + txt + ")"); document.getElementById("name").innerHTML=obj.sites[0].name document.getElementById("url").innerHTML=obj.sites[0].url


JSON parser

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

JSON parser will use JSON into JavaScript objects are safer approach. JSON JSON text parser only recognizes, but does not compile the script.

In the browser, which provides support for native JSON, and JSON parser is faster.

Newer browsers and the latest ECMAScript (JavaScript) standards are included 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


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

JSON format was originally developed  originally specified by Douglas Crockford

Reproduced in: https: //www.cnblogs.com/Firesun/p/10998407.html

Guess you like

Origin blog.csdn.net/weixin_33850015/article/details/92885487