In-depth study and understanding of json

Posted by julien on Sat, 13 Jul 2019 21:12:47 +0200

The full name of json(javascript object notation) is JavaScript object representation. It is a text format for data exchange, not a programming language, for reading structured data.

Rule of grammar

JSONl can represent three types of values.

1: Simple values,

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

Strings must be represented by double quotation marks, not single quotation marks. Numbers must be expressed in decimal, and NaN and Infinity cannot be used

JSON does not support undefined special values in javascript.
  

//Qualified Simple Value
5
"hello world"
true
null
//Unqualified Simple Values
+0x1
'hello world'
undefined
NaN
Infinity

object

Object, as a kind of miscellaneous data type, represents an orderly set of key-value pairs. The value of each key-value pair can be either a simple value or a value of a complex data type.

Compared with the literal quantities of js objects, JSON has three differences.

1: json has no concept of variables
2: In json, the key name of the object must be placed in double quotation marks.
3: json is not a js statement, so there is no semicolon at the end.
4: Two properties with the same name should not appear in the same object

{
    "name":"huochai",
    "age":29,
    "school":{
        "name":"diankeyuan",
        "location":"beijing"
    }
}
//Unqualified object
{ name: "Zhang San", 'age': 32 }//Property names must be double quotes
{};//No end semicolon is required
{ "birthday": new Date('Fri, 26 Aug 2011 07:13:10 GMT'),
  "getName": function() {
      return this.name;
  }
} // Cannot use functions and date objects

array

Arrays are also a complex data type that represents a list of ordered values that can be accessed through a numerical index. Array values can also be of any type -- simple values, objects, or arrays

JSON arrays also have no variables and semicolons. Combining arrays with objects can form more complex data sets.

[Note] No comma can be added after the last member of an array or object

json object

json is popular because it can transform json data structures into useful js objects.
EMACscript5 standardizes JSON and defines global json.

json has two methods. stringify() and parse(); these two methods serialize JS objects into json strings and parse json strings into native JS values, respectively.

stingify()

JSON.stringify() is used to convert a value into a string that conforms to the JSON format and can be restored by JSON.parse().

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

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

Specific transformation

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: "Zhang San" })// '{name":"Zhang San"}'

stringify() converts regular expressions and mathematical objects into strings of empty objects.

JSON.stringify(/foo/) // "{}"
JSON.stringify(Math) // "{}"

The stringify() method converts a date object and a wrapper object into a string.

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""

If the member of an object is undefined or a function, the member is omitted.
If the members of an array are undefined or functions, these values are converted to null.

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

If NaN or Infinity occurs in object or array members, these values are converted to null

console.log(JSON.stringify({
  a: NaN,
  b: Infinity,
  c: [ NaN,Infinity]
}));
//{"a":null,"b":null,"c":[null,null]}

The JSON.stringify() method ignores the non-traversable property of the object.

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

parameter

JSON.stringify(); In addition to sequencing js objects, you can accept two parameters, which are used to specify different ways to serialize js objects. The first parameter is a filter, which can be an array or a function, and the second parameter is an option to indicate whether to retain indentation in the json string.

Array filtering

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

The filter is valid for the first attribute of the object.

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

Filters are not valid for arrays

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

Functional parameters

The second parameter of stringify() can be a function, and the incoming function receives two parameters, the attribute name song attribute value.

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

Property names can only be strings, and keynames can be empty strings when values are not key-value pair structures

In the following code, object o is processed three times by the f function. The first key name is empty and the key value is the whole object o; the second key name is a and the key value is {b:1}; the third key name is B and 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}}' 

The value returned by the function is the value of the corresponding key. If the function returns undefined or does not return a value, the corresponding attribute is ignored.

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

The stringify() method also accepts a third parameter to increase readability of the returned json string.

  1. If it is a number, it represents the space added before each attribute (up to 10).
  2. If it is a string (up to 10), the string will be added before no 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()

Sometimes, JSON.stringify() still fails to meet the need for custom serialization of certain objects. In these cases, you can return your own JSON data format by calling the toJSON() method on the object.

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

If the toJSON() method returns undefined, then if the object containing it is embedded in another object, the value of the object becomes null. If the object containing it is a top-level object, the result is undefined.

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

The Date object deploys its own toJSON method, which automatically converts the Date object into a date string.

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

One application of the toJSON method is that regular objects can be automatically converted to strings

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

toJSON() can be used as a complement to function filters, so it is important to understand the internal order of serialization. Assuming that an object is passed into JSON.stringify(), serialize the object in the following order

1. If there is a toJSON() method and a valid value can be obtained through it, the method is called. Otherwise, serialization is performed in the default order

2. If a second parameter is provided, apply this function filter. The value of the input function filter is the value returned in the first step

3. Serialize each value returned in the second step

4. If a third parameter is provided, perform the corresponding formatting

parse()

The JSON.parse method is used to convert JSON strings into objects.

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": "Zhang San"}');
o.name // Zhang San

If the incoming string is not in a valid JSON format, the JSON.parse method will report an error.

//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")

The JSON.parse() method can also take a function parameter and call it on each key pair, which is called a reviver. This function receives two parameters, a key and a value, and returns a value.

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 // undefined

Restore functions are often used when converting date strings to Date objects

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

Topics: JSON Javascript Attribute Programming