YouTip LogoYouTip

Js Json

# JavaScript JSON * * * JSON is a format for storing and transporting data. JSON is often used to send data from a server to a web page. * * * ## What is JSON? * JSON stands for **J**ava**S**cript **O**bject **N**otation * JSON is a lightweight data interchange format. * JSON is language independent ***** * JSON is "self-describing" and easy to understand. | ![Image 2: Note](#) | * JSON uses JavaScript syntax, but the JSON format is just text. Text can be read and used as data by any programming language. | | --- | ## JSON Example The following JSON syntax defines a sites object: an array of 3 site information (objects): ## JSON Example {"sites":[{"name":"", "url":"www..com"}, {"name":"Google", "url":"www.google.com"}, {"name":"Taobao", "url":"www.taobao.com"}]} * * * ## JSON Formatted as JavaScript Objects The JSON format is syntactically identical to the code for creating JavaScript objects. Because they are so similar, JavaScript programs can easily convert JSON data into JavaScript objects. * * * ## JSON Syntax Rules * Data is in key/value pairs. * Data is separated by commas. * Curly braces hold objects. * Square brackets hold arrays. * * * ## JSON Data - A Name and a Value JSON data is written as name/value pairs, just like JavaScript object properties. A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value: "name":"" * * * ## JSON Objects JSON objects are written in curly braces. Just like in JavaScript, objects can contain multiple name/value pairs: {"name":"", "url":"www..com"} * * * ## JSON Arrays JSON arrays are written in square brackets. Just like in JavaScript, arrays can contain objects: "sites":[{"name":"", "url":"www..com"}, {"name":"Google", "url":"www.google.com"}, {"name":"Taobao", "url":"www.taobao.com"}] In the example above, the object "sites" is an array, containing three objects. Each object is a site's information (site name and site address). * * * ## Converting a JSON String to a JavaScript Object Typically we receive JSON data from a web server, and display the data on a web page. For simplicity, we set the JSON string directly in our web page (you can also read our (#)): First, create a JavaScript string, the string is JSON format data: var text = '{ "sites" : [' + '{ "name":"" , "url":"www..com" },' + '{ "name":"Google" , "url":"www.google.com" },' + '{ "name":"Taobao" , "url":"www.taobao.com" } ]}'; Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object: var obj = JSON.parse(text); Finally, use the new JavaScript object in your page: ## Example var text = '{ "sites" : [' + '{ "name":"" , "url":"www..com" },' + '{ "name":"Google" , "url":"www.google.com" },' + '{ "name":"Taobao" , "url":"www.taobao.com" } ]}'; obj = JSON.parse(text); document.getElementById("demo").innerHTML = obj.sites.name + "" + obj.sites.url; [Try it Yourself Β»](#)
← Js ScopeServlet Intro β†’