JSON (JavaScript Object Notation), JavaScript Object Notation, is a lightweight data exchange format. It is very convenient for programmers to process data, and it is also convenient for machines to parse and generate data. It is widely used.
JSON is a lightweight data exchange format. The inside of a JSON format file can look like this:
{ "name": "hanzichi", "sex": "male" }
It looks like they are all key-value pairs, very similar to js objects, right? That's right, but at the same time JSON expressed dissatisfaction. I can't look the same as the js object. I have to have my own personality, so it is stipulated that the keys in the key-value pair must use double quotes! At the same time, it is stipulated that there are certain requirements for the value of the key-value pair:
JSON value can be:
Number (integer or floating point)
String (in double quotes)
Logical value (true or false)
Array (in square brackets)
Object (in curly braces)
null
Except for the above 6 types, there are no others. There is no undefined or NAN like js, and JSON refuses to be used.
How to use JSON?
JSON generally travels in the form of strings during the data interaction process, so for js, how to convert json strings and js objects to and from each other is particularly important.
eval method (json string -> js object)
var jsonStr = '{"name": "hanzichi", "sex": "male"}'; var ans = eval('(' + jsonStr + ')'); console.log(ans.name, ans.sex); // hanzichi male
The eval function is very fast, but it can compile any javascirpt code, which may cause security issues. The use of eval is based on the assumption that the incoming code parameters are reliable. There are some cases where the client may not be trusted. If it is based on security considerations, it is best to use a JSON parser. A JSON parser will only accept JSON text, so it is safer, as follows.
JSON.parse(json字符串 -> js对象) var jsonStr = '{"name": "hanzichi", "sex": "male"}'; var obj = JSON.parse(jsonStr); console.log(typeof obj, obj); // object Object {name: "hanzichi", sex: "male"}
The second parameter can be a function, and the value can be deleted:
var jsonStr = '{"name": "hanzichi", "sex": "male", "age": 10}'; var obj = JSON.parse(jsonStr, function(key, value) { if(key === 'name') { return 'my name is ' + value; } return value; }); console.log(typeof obj, obj); // object Object {name: "my name is hanzichi", sex: "male", age: 10} JSON.stringify(js对象 -> json字符串) var obj = {name: 'hanzichi', sex: 'male', age: '10'}; var jsonStr = JSON.stringify(obj); console.log(jsonStr); // {"name":"hanzichi","sex":"male","age":"10"}
You can also add a parameter to specify the attributes that need to be converted into json strings (in array form, only js object attributes with the same name as the array will be converted):
var obj = {name: 'hanzichi', sex: 'male', age: '10'}; var jsonStr = JSON.stringify(obj, ['name']); console.log(jsonStr); // {"name":"hanzichi"}
The second parameter can also be a function, which can delete the attribute that meets the conditions (or change the attribute value. No return means abandoning the attribute, and the value of return indicates the value of the key in the json string)
var obj = {name: 'hanzichi', sex: 'male', age: '10'}; var jsonStr = JSON.stringify(obj, function(key, value) { if(key === 'name') { return 'my name is ' + value; } return value; }); console.log(jsonStr); // {"name":"my name is hanzichi","sex":"male","age":"10"}
There can also be a third parameter, which can be a number or a string.
If it is a number, it means indentation. If the number exceeds 10, it will be processed as 10.
var obj = {name: 'hanzichi', sex: 'male', age: '10'}; var jsonStr = JSON.stringify(obj, null, 4); console.log(jsonStr); // { // "name": "hanzichi", // "sex": "male", // "age": "10" // }
can also be a string. These strings will be added in front of the attributes as prefixes. Similarly, if the string length exceeds 10, only 10 will be intercepted:
var obj = {name: 'hanzichi', sex: 'male', age: '10'}; var jsonStr = JSON.stringify(obj, null, 'pre'); console.log(jsonStr); // { // pre"name": "hanzichi", // pre"sex": "male", // pre"age": "10" // }
I have a question here. I think the output should be in the following form...
{ "prename": "hanzichi", "presex": "male", "preage": "10" }
If anyone knows, please tell me...
Summary
Of course, the legendary ie8 (and below) cannot use the JSON.parse() and JSON.stringify() methods due to some defects, and eval() seems unsafe. If you want to be compatible with them, you can refer to json2.js .
The above content gives you an introduction to JSON and a summary of its usage. I hope it will be helpful to you!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

This article discusses how to use jQuery to obtain and set the inner margin and margin values of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor
