Home > Web Front-end > JS Tutorial > body text

How to use JSON

jacklove
Release: 2018-05-08 09:35:47
Original
1967 people have browsed it

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" } ]}';
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!