Home > Article > Web Front-end > How to use JSON
The use of json is very important for js. This article will explain the use of json.
Convert JSON text to JavaScript Object
One of the most common uses of JSON is to read JSON data from a web server (as file or as an HttpRequest), convert the JSON data into a JavaScript object, and then use the data in the web page.
To explain it to you more simply, we use strings as input for demonstration (instead of files).
JSON Instance - Object from String
Create a JavaScript string containing JSON syntax:
var txt = '{ "employees" : [' + '{ "firstName":"Bill" , "lastName":"Gates" },' + '{ "firstName":"George" , "lastName":"Bush" },' + '{ "firstName":"Thomas" , "lastName":"Carter" } ]}';
Since JSON syntax is a subset of JavaScript syntax, JavaScript Function eval() can be used to convert JSON text into a JavaScript object.
The eval() function uses the JavaScript compiler to parse JSON text and then generate JavaScript objects. The text must be enclosed in brackets to avoid syntax errors:
var obj = eval ("(" txt ")");
at JavaScript objects used in web pages:
Example
<p> First Name: <span id="fname"></span><br /> Last Name: <span id="lname"></span><br /> </p> <script type="text/javascript"> document.getElementById("fname").innerHTML = obj.employees[1].firstName document.getElementById("lname").innerHTML = obj.employees[1].lastName </script>
This article provides relevant explanations on the use of json. For more learning materials, please pay attention to the php Chinese website.
Related recommendations:
Understand the relevant syntax of json
##Initial understanding of JSON
About PHP filter (Filter) related knowledge
The above is the detailed content of How to use JSON. For more information, please follow other related articles on the PHP Chinese website!