YouTip LogoYouTip

Json Eval

# JSON Usage * * * ## Converting JSON Text into JavaScript Objects 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 JavaScript objects, and then use that data in your web page. For simplicity, we'll demonstrate using strings as input (rather than files). * * * ## JSON Example - Object from String Create a JavaScript string containing JSON syntax: var txt = '{ "sites" : [' + '{ "name":"Rookie Tutorial" , "url":"www." },' + '{ "name":"google" , "url":"www.google.com" },' + '{ "name":"Weibo" , "url":"www.weibo.com" } ]}'; 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 the JSON text and then generate a JavaScript object. The text must be enclosed in parentheses to avoid syntax errors: var obj = eval ("(" + txt + ")"); Use the JavaScript object in your web page: ## Example var txt = '{ "sites" : [' + '{ "name":"Rookie Tutorial" , "url":"www." },' + '{ "name":"google" , "url":"www.google.com" },' + '{ "name":"Weibo" , "url":"www.weibo.com" } ]}'; var obj = eval("(" + txt + ")"); document.getElementById("name").innerHTML=obj.sites.name document.getElementById("url").innerHTML=obj.sites.url [Try it Β»]( * * * ## JSON Parser ![Image 2: lamp]( The eval() function can compile and execute any JavaScript code. This hides a potential security risk. Using a JSON parser to convert JSON into JavaScript objects is a safer approach. 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) standards both include native support for JSON. | Web Browser Support | Web Software Support | | --- | --- | | * 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, you can use the JavaScript library: [https://github.com/douglascrockford/JSON-js](https://github.com/douglascrockford/JSON-js) JSON format was originally specified by Douglas Crockford
← Jquery IntroJson Syntax β†’