什么是JSON?
JSON是一种轻量级的数据交换格式
什么是JSON?
JavaScript 对象表示法(JavaScript Object Notation)。
JSON是一种轻量级的数据交换格式,某个JSON格式的文件内部譬如可以长成这样:
{
"name": "hanzichi",
"sex": "male"
}
看起来都是key-value的键值对,很像js的对象吧?没错,但同时JSON表示不服,我不能跟js的对象长成一样啊,我得有我自己的个性,于是规定键-值对中的键必须用双引号!同时规定键-值对中的值的取值有一定要求:
JSON 值可以是:
数字(整数或浮点数)
字符串(在双引号中)
逻辑值(true 或 false)
数组(在方括号中)
对象(在花括号中)
null
除以上6种外,再无其他,没有像js一样的undefined、NAN,JSON拒绝使用。
如何使用JSON?
JSON一般以字符串的形式在数据交互过程中游走,so对于js而言,如何将json字符串和js对象之间进行相互转换显得尤为重要。
eval大法(json字符串 -> js对象)
var jsonStr = '{"name": "hanzichi", "sex": "male"}';
var ans = eval('(' + jsonStr + ')');
console.log(ans.name, ans.sex); // hanzichi male
eval 函数非常快,但是它可以编译任何 javascirpt 代码,这样的话就可能产生安全的问题。eval 的使用是基于传入的代码参数是可靠的假设下,有一些情况下,可能客户端是不可信任的。如果基于安全的考虑的话,最好是使用一个JSON解析器,一个JSON 解析器将只接受JSON文本,所以是更安全的,如下。
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"}
第二个参数可以是函数,可以对值进行删改:
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"}
也可以加个参数,规定需要转化为json字符串的属性(数组形式,跟数组同名的js对象属性才会被转换):
var obj = {name: 'hanzichi', sex: 'male', age: '10'};
var jsonStr = JSON.stringify(obj, ['name']);
console.log(jsonStr); // {"name":"hanzichi"}
第二个参数也可以是个函数,可以删选符合条件的属性(或者改变属性值,没有return表示放弃该属性,return的值表示该key在json字符串中的值)
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"}
还可以有第三个参数,可以是数字或者字符串。
如果是数字的话,表示缩进,数字大小超过10了按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"
// }
也可以是字符串,会在属性前加上这些字符串充当前缀,同样字符串长度超过10只截取10:
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"
// }
这里我有个疑问,我觉得输出应该是如下形式才对啊...
{
"prename": "hanzichi",
"presex": "male",
"preage": "10"
}
麻烦有知道的大大能倾情告诉我...
总结
当然传说中的ie8(及以下)因为某种缺陷不能使用JSON.parse()以及JSON.stringify()方法,而eval()又显得不安全,如果要兼容它们的话可以引用json2.js。
AD:真正免费,域名+虚机+企业邮箱=0元

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Learn about Python programming with introductory code examples Python is an easy-to-learn, yet powerful programming language. For beginners, it is very important to understand the introductory code examples of Python programming. This article will provide you with some concrete code examples to help you get started quickly. Print HelloWorldprint("HelloWorld") This is the simplest code example in Python. The print() function is used to output the specified content

PHP variables store values during program runtime and are crucial for building dynamic and interactive WEB applications. This article takes an in-depth look at PHP variables and shows them in action with 10 real-life examples. 1. Store user input $username=$_POST["username"];$passWord=$_POST["password"]; This example extracts the username and password from the form submission and stores them in variables for further processing. 2. Set the configuration value $database_host="localhost";$database_username="username";$database_pa

Title: From Beginner to Mastery: Code Implementation of Commonly Used Data Structures in Go Language Data structures play a vital role in programming and are the basis of programming. In the Go language, there are many commonly used data structures, and mastering the implementation of these data structures is crucial to becoming a good programmer. This article will introduce the commonly used data structures in the Go language and give corresponding code examples to help readers from getting started to becoming proficient in these data structures. 1. Array Array is a basic data structure, a group of the same type

"Go Language Programming Examples: Code Examples in Web Development" With the rapid development of the Internet, Web development has become an indispensable part of various industries. As a programming language with powerful functions and superior performance, Go language is increasingly favored by developers in web development. This article will introduce how to use Go language for Web development through specific code examples, so that readers can better understand and use Go language to build their own Web applications. 1. Simple HTTP Server First, let’s start with a

The simplest code example of Java bubble sort Bubble sort is a common sorting algorithm. Its basic idea is to gradually adjust the sequence to be sorted into an ordered sequence through the comparison and exchange of adjacent elements. Here is a simple Java code example that demonstrates how to implement bubble sort: publicclassBubbleSort{publicstaticvoidbubbleSort(int[]arr){int

How to use PHP to write the inventory management function code in the inventory management system. Inventory management is an indispensable part of many enterprises. For companies with multiple warehouses, the inventory management function is particularly important. By properly managing and tracking inventory, companies can allocate inventory between different warehouses, optimize operating costs, and improve collaboration efficiency. This article will introduce how to use PHP to write code for inventory warehouse management functions, and provide you with relevant code examples. 1. Establish the database before starting to write the code for the inventory warehouse management function.

Java Selection Sorting Method Code Writing Guide and Examples Selection sorting is a simple and intuitive sorting algorithm. The idea is to select the smallest (or largest) element from the unsorted elements each time and exchange it until all elements are sorted. This article will provide a code writing guide for selection sorting, and attach specific Java sample code. Algorithm Principle The basic principle of selection sort is to divide the array to be sorted into two parts, sorted and unsorted. Each time, the smallest (or largest) element is selected from the unsorted part and placed at the end of the sorted part. Repeat the above

Huawei Cloud Edge Computing Interconnection Guide: Java Code Samples to Quickly Implement Interfaces With the rapid development of IoT technology and the rise of edge computing, more and more enterprises are beginning to pay attention to the application of edge computing. Huawei Cloud provides edge computing services, providing enterprises with highly reliable computing resources and a convenient development environment, making edge computing applications easier to implement. This article will introduce how to quickly implement the Huawei Cloud edge computing interface through Java code. First, we need to prepare the development environment. Make sure you have the Java Development Kit installed (
