Table of Contents
JSON basic syntax
Simple type values
objects
Array
JSON parsing and serialization
JSON object
缩进
空格填充
字符填充
toJSON()方法
序列化对象顺序
parse解析
小结
Home Web Front-end JS Tutorial Lightweight data format - JSON

Lightweight data format - JSON

Feb 28, 2017 pm 03:09 PM

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)!


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)

Combination of golang WebSocket and JSON: realizing data transmission and parsing Combination of golang WebSocket and JSON: realizing data transmission and parsing Dec 17, 2023 pm 03:06 PM

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

Best lightweight Linux distributions for low-end or older computers Best lightweight Linux distributions for low-end or older computers Mar 06, 2024 am 09:49 AM

Looking for the perfect Linux distribution to breathe new life into your old or low-end computer? If yes, then you have come to the right place. In this article, we'll explore some of our top picks for lightweight Linux distributions that are specifically tailored for older or less powerful hardware. Whether the motivation behind this is to revive an aging device or simply maximize performance on a budget, these lightweight options are sure to fit the bill. Why choose a lightweight Linux distribution? There are several advantages to choosing a lightweight Linux distribution, the first of which is getting the best performance on the least system resources, which makes them ideal for older hardware with limited processing power, RAM, and storage space. Beyond that, with heavier resource intensive

What is the difference between MySQL5.7 and MySQL8.0? What is the difference between MySQL5.7 and MySQL8.0? Feb 19, 2024 am 11:21 AM

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

How to handle XML and JSON data formats in C# development How to handle XML and JSON data formats in C# development Oct 09, 2023 pm 06:15 PM

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string Nov 18, 2023 pm 01:59 PM

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string. When writing programs in Golang, we often need to convert the structure into a JSON string. In this process, the json.MarshalIndent function can help us. Implement formatted output. Below we will explain in detail how to use this function and provide specific code examples. First, let's create a structure containing some data. The following is an indication

Pandas usage tutorial: Quick start for reading JSON files Pandas usage tutorial: Quick start for reading JSON files Jan 13, 2024 am 10:15 AM

Quick Start: Pandas method of reading JSON files, specific code examples are required Introduction: In the field of data analysis and data science, Pandas is one of the important Python libraries. It provides rich functions and flexible data structures, and can easily process and analyze various data. In practical applications, we often encounter situations where we need to read JSON files. This article will introduce how to use Pandas to read JSON files, and attach specific code examples. 1. Installation of Pandas

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

See all articles