search
HomeWeb Front-endJS TutorialUsing JSON data in JavaScript_javascript tips

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" }
]
}

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;

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"

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";

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 格式的文本)

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();

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>

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 + ')');

or

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

or

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

Then, you can read it like this:

Alert(obj.name);
Alert(obj.sex);

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
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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

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 Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools