Home > Web Front-end > JS Tutorial > body text

JSON object (graphic tutorial, simple and crude)

亚连
Release: 2018-05-19 15:25:48
Original
1551 people have browsed it

This article mainly introduces the relevant information on the detailed explanation of JSON objects, and attaches simple example codes to help everyone learn and reference. Friends in need can refer to the previous words

The full name of json (javascript object notation) is javascript object notation. It is a text format for data exchange, not a programming language, used to read structured data. It was proposed by Douglas Crockford in 2001 with the purpose of replacing the cumbersome and cumbersome XML format. This article will introduce in detail the content of json

Grammar rules

The syntax of JSON can represent the following three types of values

[1] Simple value

Simple values ​​use the same syntax as JavaScript and can represent strings, numeric values, Boolean values, and null in JSON

Strings must be represented by double quotes, single quotes cannot be used. The value must be expressed in decimal, and NaN and Infinity

cannot be used [Note] JSON does not support the special value undefined

//合格的简单值
5
"hello world"
true
null
Copy after login
//不合格的简单值
+0x1
'hello world'
undefined
NaN
Infinity
Copy after login

[2] Object

The object is used as an A complex data type that represents an ordered set of key-value pairs. The value in each key-value pair can be a simple value or a complex data type value

Compared with JavaScript object literals, json has three differences

1. JSON does not have the concept of variables

2. In JSON, the key name of the object must be placed in double quotes

3. Because JSON is not a javascript statement, there is no semicolon at the end

[Note] Two properties with the same name should not appear in the same object

//合格的对象
{
  "name":"huochai",
  "age":29,
  "school":{
    "name":"diankeyuan",
    "location":"beijing"
  }
}
Copy after login
//不合格的对象
{ name: "张三", 'age': 32 }//属性名必须使用双引号
{};//不需要末尾的分号
{ "birthday": new Date('Fri, 26 Aug 2011 07:13:10 GMT'),
 "getName": function() {
   return this.name;
 }
} // 不能使用函数和日期对象
Copy after login

[3] Array

Array is also a complex data type, representing a set of ordered values. A list whose values ​​can be accessed by numeric index. The value of the array can also be of any type - simple value, object or array

JSON array also has no variables and semicolons. Combining arrays and objects can form more complex data collections

[Note] A comma cannot be added after the last member of an array or object

JSON object

The reason why JSON is popular is that the JSON data structure can be parsed as Useful javascript objects

ECMAScript5 standardizes the behavior of parsing JSON and defines the global object JSON

[Note] IE7-browser does not support

There are two JSON objects Methods: stringify() and parse(). These two methods are used to serialize JavaScript objects into JSON strings and parse JSON strings into native JavaScript values.

stringify()

The JSON.stringify() method is used to Convert a value to a string. The string should conform to JSON format and can be restored by the JSON.parse() method

By default, the JSON string output by JSON.stringify() does not include any space characters or indentation

var jsonObj = {
  "title":"javascript",
  "group":{
    "name":"jia",
    "tel":12345
  }
};
//{"title":"javascript","group":{"name":"jia","tel":12345}}
JSON.stringify(jsonObj);
Copy after login

Specific conversion

JSON.stringify('abc') // ""abc""
JSON.stringify(1) // "1"
JSON.stringify(false) // "false"
JSON.stringify([]) // "[]"
JSON.stringify({}) // "{}"
JSON.stringify([1, "false", false])// '[1,"false",false]'
JSON.stringify({ name: "张三" })// '{"name":"张三"}'
Copy after login

The stringify() method converts regular expressions and mathematical objects into the string form of empty objects

JSON.stringify(/foo/) // "{}"
JSON.stringify(Math) // "{}"
Copy after login

The stringify() method converts dates Objects and wrapper objects are converted to strings

JSON.stringify(new Boolean(true)) //"true"
JSON.stringify(new String('123')) //""123""
JSON.stringify(new Number(1)) //"1"
JSON.stringify(new Date()) //""2016-09-20T02:26:38.294Z""
Copy after login

If the members of the object are undefined or functions, this member will be omitted

If the members of the array are undefined or functions, these values ​​​​are converted to null

JSON.stringify({
 a: function(){},
 b: undefined,
 c: [ function(){}, undefined ]
});
// "{"c":[null,null]}"
Copy after login

 The JSON.stringify() method will ignore the non-traversable properties of the object

var obj = {};
Object.defineProperties(obj, {
 'foo': {
  value: 1,
  enumerable: true
 },
 'bar': {
  value: 2,
  enumerable: false
 }
});
JSON.stringify(obj); // {"foo":1}]
Copy after login

Parameters

 JSON.stringify() except for serialization In addition to the JavaScript object, it can also receive two other parameters, which are used to specify different ways to serialize the JavaScript object. The first parameter is a filter, which can be an array or a function; the second parameter is an option, indicating whether to retain indentation in the JSON string

[Array Filter]

When the second parameter of the stringify() method is an array, it is equivalent to realizing the function of a filter.

[1] The filter is only effective for the first layer properties of the object

var jsonObj = {
  "title":"javascript",
  "group":{
    "a":1
  }
};
//{"group":{"a":1}}
console.log(JSON.stringify(jsonObj,["group","a"]))
Copy after login

 【2】Filter is invalid for arrays

var jsonObj =[1,2];
JSON.stringify(jsonObj,["0"])//"[1,2]"
Copy after login

[Function parameters]

 The second parameter of the stringify() method can also be a function. The passed-in function receives two parameters, the attribute (key) name and the attribute value

JSON.stringify({a:1,b:2}, function(key, value){
 if (typeof value === "number") {
  value = 2 * value;
 }
 return value;  
})
// "{"a":2,"b":4}"
Copy after login

. The attribute name can only be a string, and when the value is not the value of the key-value pair structure, the key name can be an empty character. String

This function parameter will recursively process all keys

In the following code, object o will be processed by the f function three times in total. The first time the key name is empty, the key value is the entire object o; the second time the key name is a, the key value is {b:1}; the third time the key name is b, the key value is 1

JSON.stringify({a: {b: 1}}, function (key, value) {
 console.log("["+ key +"]:" + value);
 return value;
})
// []:[object Object]
// [a]:[object Object]
// [b]:1
// '{"a":{"b":1}}'
Copy after login

The value returned by the function is the value of the corresponding key. If the function returns undefined or has no return value, the corresponding properties will be ignored

JSON.stringify({ a: "abc", b: 123 }, function (key, value) {
 if (typeof(value) === "string") {
  return undefined;
 }
 return value;
})
// '{"b": 123}'
Copy after login

[Indent]

The stringify() method can also accept a third parameter to increase the return The readability of the JSON string

If it is a number, it means the space added in front of each attribute (no more than 10)

If it is a string (no more than 10 characters) , the string will be added in front of each line

/*"{
 "p1": 1,
 "p2": 2
}"*/
JSON.stringify({ p1: 1, p2: 2 }, null, 2);
//"{"p1":1,"p2":2}"
JSON.stringify({ p1: 1, p2: 2 }, null, 0);
/*"{
|-"p1": 1,
|-"p2": 2
}"*/
JSON.stringify({ p1:1, p2:2 }, null, '|-');
toJSON()
Copy after login

Sometimes, JSON.stringify() still cannot meet the needs for custom serialization of certain objects. In these cases, you can call the toJSON() method on the object to return its own JSON data format

JSON.stringify({
 toJSON: function () {
  return "Cool"
 }
})
// ""Cool""
Copy after login
var o = {
 foo: 'foo',
 toJSON: function() {
  return 'bar';
 }
};
JSON.stringify({x: o});// '{"x":"bar"}'
Copy after login

  如果toJSON()方法返回undefined,此时如果包含它的对象嵌入在另一个对象中,会导致该对象的值变成null。而如果包含它的对象是顶级对象,结果就是undefined

JSON.stringify({
 toJSON: function () {
  return undefined
 }
})
//undefined
Copy after login

  Date对象部署了一个自己的toJSON方法,自动将Date对象转换成日期字符串

JSON.stringify(new Date("2016-08-29"))
// "2016-08-29T00:00:00.000Z"
Copy after login

  toJSON方法的一个应用是,可以将正则对象自动转为字符串

RegExp.prototype.toJSON =RegExp.prototype.toString;
JSON.stringify(/foo/)// ""/foo/""
Copy after login

  toJSON()可以作为函数过滤器的补充,因此理解序列化的内部顺序十分重要。假设把一个对象传入JSON.stringify(),序列化该对象的顺序如下

  1、如果存在toJSON()方法而且能通过它取得有效的值,则调用该方法。否则,按默认顺序执行序列化

  2、如果提供了第二个参数,应用这个函数过滤器。传入函数过滤器的值是第一步返回的值

  3、对第二步返回的每个值进行相应的序列化

  4、如果提供了第三个参数,执行相应的格式化

parse()

  JSON.parse方法用于将JSON字符串转化成对象

JSON.parse('{}') // {}
JSON.parse('true') // true
JSON.parse('"foo"') // "foo"
JSON.parse('[1, 5, "false"]') // [1, 5, "false"]
JSON.parse('null') // null
var o = JSON.parse('{"name": "张三"}');
o.name // 张三
Copy after login

  如果传入的字符串不是有效的JSON格式,JSON.parse方法将报错

//Uncaught SyntaxError: Unexpected token u in JSON at position 0(…)
JSON.parse("'String'")

//Uncaught SyntaxError: Unexpected token u in JSON at position 0(…)
JSON.parse("undefined")
  JSON.parse()方法也可以接收一个函数参数,在每个键值对儿上调用,这个函数被称为还原函数(reviver)。该函数接收两个参数,一个键和一个值,返回一个值

  如果还原函数返回undefined,则表示要从结果中删除相应的键;如果返回其他值,则将该值插入到结果中

var o = JSON.parse('{"a":1,"b":2}', function(key, value) {
 if (key === ''){
  return value;
 }
 if (key === 'a') {
  return value + 10;
 }
});
o.a // 11
o.b // undefinef
Copy after login

  在将日期字符串转换为Date对象时,经常要用到还原函数

var book = {
  "title": "javascript",
  "date": new Date(2016,9,1)
}
var jsonStr = JSON.stringify(book);
//'{"title":"javascript","date":"2016-09-30T16:00:00.000Z"}''
console.log(jsonStr)

var bookCopy = JSON.parse(jsonStr,function(key,value){
  if(key == 'date'){
    return new Date(value);
  }
  return value;
})
console.log(bookCopy.date.getFullYear());//2016
Copy after login

eval()

  实际上,eval()类似于JSON.parse()方法,可以将json字符串转换为json对象

eval('(' + '{"a":1}'+')').a;//1
JSON.parse('{"a":1}').a;//1
Copy after login

  但是,eval()可以执行不符合JSON格式的代码,有可能会包含恶意代码

eval('(' + '{"a":alert(1)}'+')').a;//弹出1
JSON.parse('{"a":alert(1)}').a;//报错
Copy after login

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

原生js实现节日时间倒计时功能(附上代码)

关于在不同页面之间实现参数传递的几种方式(详细为你解答)

详细为你解读JavaScript字符集编码与解码(图文教程)

The above is the detailed content of JSON object (graphic tutorial, simple and crude). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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