Home Web Front-end JS Tutorial Using JSON data in JavaScript_javascript tips

Using JSON data in JavaScript_javascript tips

May 16, 2016 pm 03:15 PM

JSON is a native JavaScript format, which means that processing JSON data in JavaScript does not require any special API or toolkit.

JSON syntax

JSON is constructed from two structures:

Object - a collection of name/value pairs. In different languages, it is understood as an object, record, structure, dictionary, hash table, keyed list, or associative array. An object starts with "{" (left bracket) and ends with "}" (right bracket). Each "name" is followed by a ":" (colon); "name/value" pairs are separated by a "," (comma).

Array - An ordered list of values. In most languages, it is understood as an array. An array starts with "[" (left bracket) and ends with "]" (right bracket). Values ​​are separated by "," (comma).

JSON has no variables or other control structures. JSON is only used for data transfer.

Assign JSON data to variables

For example, you can create a new JavaScript variable and assign a JSON-formatted data string directly to it:

var people =
{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
]
}
Copy after login

This is very simple; now people contains the data in the JSON format we saw earlier. However, this is not enough as the way to access the data does not seem obvious yet.

Access Data

Although it may not seem obvious, the long string above is actually just an array; you can easily access this array by placing it in a JavaScript variable. In fact, just use dot notation to represent array elements. So, to access the last name of the first entry in the programmers list, just use code like this in JavaScript:

people.programmers[0].lastName;
Copy after login

Note that array indexing is zero-based. So, this line of code first accesses the data in the people variable; then moves to the entry called programmers , then moves to the first record ( [0] ); and finally, accesses the value of the lastName key. The result is the string value "McLaughlin" .

Here are a few examples using the same variable.

people.authors[1].genre 
// Value is "fantasy"
people.musicians[3].lastName 
// Undefined. This refers to the fourth entry,and there isn't one
people.programmers[2].firstName 
// Value is "Elliotte"
Copy after login

Using this syntax, you can process any JSON format data without using any additional JavaScript toolkit or API.

Modify JSON data

Just as data can be accessed using periods and brackets, data can be easily modified in the same way:

people.musicians[1].lastName = "Rachmaninov";
Copy after login

After converting the string into a JavaScript json format object, you can modify the data in the variable like this.

Note: json format objects and json text are different

var obj={name:" 张三 ","sex":' 男 '}; //json 格式的对象
var str=" { name: " 张三 " , "sex" : ' 男 ' }" ; //json 格式的字符串( json 格式的文本)
Copy after login

Convert back to string

Of course, all data modifications are of little value if you can't easily convert the object back to the text format mentioned in this article. This conversion is also simple in JavaScript:

var newJSONtext = people.toJSONString();
Copy after login

That’s it! You now have a text string that you can use anywhere, for example, as a request string in an Ajax application.

More importantly, any JavaScript object can be converted to JSON text. It is not only possible to handle variables originally assigned with JSON strings. To convert an object named myObject, just execute a command of the same form:

<script type="text/javascript">
function Car(make,model,year,color)
{
this.make=make; 
this.model=model; 
this.year=year; 
this.color=color;
} 
function showCar()
{
var carr = new Car("Dodge","Coronet R/T",1968,"yellow"); 
alert(carr.toJSONString()); 
}
</script>
Copy after login

This is the biggest difference between JSON and other data formats. If you use JSON, you only need to call a simple function to get the formatted data, which is ready to use. For other data formats, conversion between raw and formatted data is required. Even when using an API like the Document Object Model (which provides functions for converting your own data structures into text), you need to learn the API and use the API's objects instead of using native JavaScript objects and syntax.

The final conclusion is that if you are dealing with a large number of JavaScript objects, then JSON is almost certainly a good choice so that you can easily convert the data into a format that can be sent to the server-side program in the request (Ajax).

Method to convert JSON string to JSON object

To use the str1 above, you must first convert it into a JSON object using the following method:

//由JSON字符串转换为JSON对象
var obj = eval('(' + str + ')');
Copy after login

or

var obj = str.parseJSON(); //由JSON字符串转换为JSON对象
Copy after login

or

var obj = JSON.parse(str); //由JSON字符串转换为JSON对象
Copy after login

Then, you can read it like this:

Alert(obj.name);
Alert(obj.sex);
Copy after login

Special note: If obj is originally a JSON object, then it will still be a JSON object after using the eval() function to convert it (even if it is converted multiple times), but there will be problems after using the parseJSON() function to process it (throwing a syntax exception) .

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles