Home > Web Front-end > JS Tutorial > Lightweight data format - JSON

Lightweight data format - JSON

黄舟
Release: 2017-02-28 15:09:25
Original
1503 people have browsed it

I really can’t stand this mathematics today

Let’s change my mind and write about the front end
Today I will write a little knowledge JSON


A long time ago , XML is the standard for transmitting data on the Internet
But everyone generally thinks that XML is too cumbersome
Later, with the development of the Web
People found that JSON is more convenient to use as a subset of JavaScript syntax
So JSON It has become a standard
Now everyone uses JSON as the data format for communication

JSON basic syntax

(JSON: JavaScript Object Notation, JavaScript object Representation)
JSON syntax is roughly divided into three types of values

  • Simple type values: can represent strings, numbers, Boolean values ​​and null

  • Object: complex data type, representing unordered key-value pairs

  • Array: complex data type, representing an ordered list of values

Note that JSON does not support undefined or functions

Simple type values

A separate basic type value can also be regarded as JSON
Syntax and JavaScript Same
Just one thing to note
In our JavaScript, strings can be represented by double quotes or single quotes
However, the string format in JSON must use double quotes

objects

Since JSON is a subset of JavaScript syntax
, I will mainly talk about the differences
Let’s first look at our commonly used object literal declaration format

var man = {
    name: 'payen',
    sex: 'male',
    age: 19};
Copy after login

Our JavaScript Objects in JSON can add quotes or not
(in order to distinguish ordinary objects from JSON objects, quotes are usually not added)
But in JSON objects require (double) quotes to be added to the properties
Our above Objects can also be written like this in JavaScript, which is completely equivalent to

var man = {    "name": "payen",    "sex": "male",    "age": 19};
Copy after login

. Using JSON to represent the above object is

{
    "name": "payen",
    "sex": "male",
    "age": 19}
Copy after login

(there is no concept of variables and no semicolon in JSON)
Of course The value of an object in JSON can also be an object
No matter how complex the JSON is, the key (property) of the object must be enclosed in (double) quotes

Array

Although in our JavaScript, Strictly speaking, arrays belong to objects
But we usually treat them differently
Our common method of declaring array literals

var value = [123, 'abc', true];
Copy after login

JSON also has the same syntax

[123, "abc", true]
Copy after login

Emphasis again , JSON does not have variables and semicolons


Generally speaking, arrays and objects are the outermost forms of JSON
Various JSON data can be constructed through arrays, objects and simple type values Format

JSON parsing and serialization

The more important reason why JSON is popular
is that it is easier to parse into useful objects

JSON object

Early JSON parsers used JavaScript's eval()
But it is risky and may execute malicious code
ES5 standardizes the behavior of parsing JSON
Definition of global objects JSON
It has two methods

  • stringify()
    JavaScript object–> JSON string

  • parse()
    JSON string–> JavaScript object

The most basic usage is of course
We pass the variable to be converted as a parameter
For example (this The example will be used forever)

var man = {    &#39;name&#39;: "payen", <--
    sex: "male", <--
    "age": 19,    "school": {        "name": &#39;HUST&#39;,        "sex": undefined, <--
        "location": function(){} <--
    }
}
var str = JSON.stringify(man);
console.log(str);
console.log(typeof str);
Copy after login

Let’s take a look at the console print

We can see that JSON.stringify really returns the JSON string
We have no quotes There are also single-quoted attributes that have become double-quoted in the JSON string
and the attribute value is undefined or the function's attributes are automatically ignored
(prototype members are even ignored)

Although JSON.stringify() will automatically ignore undefined and function (including ES6 symbols) in objects
But arrays are different
Arrays have no objects and kick them away ruthlessly, but return null

console.log(JSON.stringify([123, undefined, null, function(){}]));
Copy after login


We can use JSON.parse to restore it to a JavaScript object

console.log(JSON.parse(str));
Copy after login
Copy after login

##Let’s take a look See the in-depth usage of these two functions

stringify serialization

In addition to filling in the object to be serialized, this method can also accept two parameters

One is a filter, It can be an array or a function
The second is to specify the indentation of the JSON string

Filter

Array filter

The form of the array is relatively simple , we can specify the object attributes we want

or our example above

var str = JSON.stringify(man,[&#39;name&#39;,&#39;sex&#39;]);
console.log(str);
Copy after login

Function filter

The function we pass in receives the connection Parameters, key (property name) and value (property value)

The returned value is the value of the corresponding key
If the function returns undefined, the property will be ignored

var str = JSON.stringify(man, function(key, value){
    if(key == &#39;name&#39;){        return &#39;abc&#39;;
    }    if(key == &#39;sex&#39;){        return;
    }    return value;
});
console.log(str);
Copy after login


注意这里最后一定要写return value; 才能正常显示其他值
如果使用了switch语句就写default: return value;

缩进

空格填充

另一个参数可以填写数字指定缩进的空格数(最大缩进10)

var str = JSON.stringify(man, null, 4);
console.log(str);
Copy after login

字符填充

我们也可以指定缩进字符

var str = JSON.stringify(man, null, "- - ");
console.log(str);
Copy after login

toJSON()方法

可能有些时候stringify不够满足我们的需求
这时我们可以给对象定义toJSON()方法
(但仍然是调用stringify()方法)
返回自身的JSON的数据格式
原生Date对象有默认toJSON()返回日期字符串(同Date中方法toISOString()结果相同)

我们可以给我们的对象添加一个toJSON属性

var man = {    ...,
    toJSON: function(){        return this.school;
    }
}
var str = JSON.stringify(man);
console.log(str);
Copy after login

这里再多说一句
很多同学误认为toJSON()返回的是JSON字符串
其实不是的
toJSON()返回的应该是一个适当的值,然后由JSON.stringify()对其进行序列化
所以toJSON()是返回一个能够被字符串化的安全JSON值
下面我们来看看调用JSON.stringify()发生了什么

序列化对象顺序

  • 如果对象有toJSON()并且能获得有效值,优先调用,否则返回对象本身

  • 若有第二个参数,对上一步返回的对象应用过滤器

  • 对上一步返回的每个值进行相应序列化

  • 若有第三个参数,执行序列化

parse解析

JSON.parse也可以接受另一个参数,它是一个函数
类似于上面序列化中过滤器的过滤函数
它被称作还原函数,同样接受键和值作为参数
首先我现在我们例子中的对象添加一个方法

var man = {    ...,
    releaseDate: new Date(2016,11,11)
}
var str = JSON.stringify(man);
console.log(str);
Copy after login


我们看到,由于Date对象存在toJSON()
序列化之后调用了toJSON()
我们看到了这样的字符串

console.log(JSON.parse(str));
Copy after login
Copy after login


这样的数据不是我们想要的
这样的情况我们怎么处理呢?
答案是使用还原函数


可以这样做

var msg = JSON.parse(str,function(key, value){
    if(key == &#39;releaseDate&#39;){        return new Date(value);
    }else{        return value;
    }
})
console.log(msg.releaseDate.getFullYear(),
            msg.releaseDate.getMonth(),
            msg.releaseDate.getDate());
Copy after login

这样我们就可以使用得到的时间数据了

小结

没想到写了这么多
JSON其实很简单
就是一个轻量级的数据格式
可以简化表示复杂数据结构的工作量
主要要掌握ES5的全局对象JSON中的两个方法JSON.stringify()和JSON.parse()
总结几个要记住的重点

  • JSON.stringify()
    用于把JavaScript对象转换为JSON字符串
    可填写额外两个参数-筛选数组/替换函数和指定缩进

    • 对象遇到undefined、function、symbol(ES6)会忽略

    • 数组遇到undefined、function、symbol(ES6)会返回null

  • JSON.parse()
    用于把JSON字符串转换为JavaScript对象
    可填写额外一个参数-还原函数

 以上就是轻量级数据格式——JSON的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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