Home  >  Article  >  Web Front-end  >  How to use JSON

How to use JSON

jacklove
jackloveOriginal
2018-05-08 09:35:471967browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn