JSON对象示例:解释字符串化和解析方法

JSON Stringify (JSON Stringify)

The JSON.stringify() method converts a JSON-safe JavaScript value to a JSON compliant string.

JSON.stringify()方法将JSON安全的 JavaScript值转换为JSON兼容的字符串。

What are JSON-safe values one may ask! Let’s make a list of all JSON-unsafe values and anything that isn’t on the list can be considered JSON-safe.

人们可能会问什么是JSON安全值! 让我们列出所有JSON不安全值,并将列表中未包含的所有内容视为JSON安全。

JSON不安全值: (JSON-unsafe values:)
  • undefined

    undefined

  • function(){}

    function(){}

  • (ES6+) Symbol

    (ES6 +) Symbol

  • An object with circular reference(s) in it

    其中包含循环引用的对象
句法 (Syntax)
JSON.stringify( value [, replacer [, space]])

In its simplest and most used form:

最简单,最常用的形式:

JSON.stringify( value )
参量 (Parameters)

value : The JavaScript value to be ‘stringified’.

value :要“字符串化”JavaScript值。

replacer : (Optional) A function or an array which serves as a filter for properties of the value object to be included in the JSON string.

replacer :(可选)一个函数或数组,用作要包含在JSON字符串中的value对象的属性的过滤器。

space : (Optional) A numeric or string value to provide indentation to the JSON string. If a numeric value is provided, that many spaces (upto 10) act as indentaion at each level. If a string value is provided, that string (upto first 10 chracters) acts as indentation at each level.

space :(可选)用于为JSON字符串提供缩进的数字或字符串值。 如果提供了数值,则每个级别上有许多空格(最多10个)用作缩进。 如果提供了字符串值,则该字符串(最多前10个字符)在每个级别上都作为缩进。

返回类型 (Return type)

The return type of the method is: string.

该方法的返回类型为: string

描述 (Description)

The JSON-safe values are converted to their corresponding JSON string form. The JSON-unsafe values on the other hand return :

JSON安全值将转换为它们对应的JSON字符串形式。 另一方面,JSON-unsafe值返回:

  • undefined if they are passed as values to the method

    如果将它们作为值传递给方法,则undefined

  • null if they are passed as an array element

    如果它们作为数组元素传递,则为null

  • nothing if passed as properties on an object

    如果作为对象的属性传递则没有
  • throws an error if its an object with circular references(s) on it.

    如果其上有循环引用的对象抛出错误。
//JSON-safe values
  JSON.stringify({});                  // '{}'
  JSON.stringify(true);                // 'true'
  JSON.stringify('foo');               // '"foo"'
  JSON.stringify([1, 'false', false]); // '[1,"false",false]'
  JSON.stringify({ x: 5 });            // '{"x":5}'
  JSON.stringify(new Date(2006, 0, 2, 15, 4, 5))  // '"2006-01-02T15:04:05.000Z"'
  
  //JSON-unsafe values passed as values to the method
  JSON.stringify( undefined );					// undefined
  JSON.stringify( function(){} );					// undefined

  //JSON-unsafe values passed as array elements
  JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] });  // '{"x":[10,null,null,null]}' 
 
 //JSON-unsafe values passed as properties on a object
  JSON.stringify({ x: undefined, y: Object, z: Symbol('') });  // '{}'
  
  //JSON-unsafe object with circular reference on it
  var o = { },
    a = {
      b: 42,
      c: o,
      d: function(){}
    };

  // create a circular reference inside `a`
  o.e = a;

  // would throw an error on the circular reference
  // JSON.stringify( a );

JSON.stringify(...) behaves differently if an object passed to it has a toJSON() method defined on it. The return value from the toJSON() method will be serialized instead of the object itself.

如果传递给它的对象具有在其上定义的toJSON()方法,则JSON.stringify(...)行为会有所不同。 toJSON()方法的返回值将被序列化,而不是对象本身。

This comes in exceptionally handy when an object contains any illegal JSON value.

当对象包含任何非法的JSON值时,这特别方便。

//JSON-unsafe values passed as properties on a object
   var obj = { x: undefined, y: Object, z: Symbol('') };
   
   //JSON.stringify(obj);  logs '{}'
   obj.toJSON = function(){
    return {
      x:"undefined",
      y: "Function",
      z:"Symbol"
    }
   }
   JSON.stringify(obj);  //"{"x":"undefined","y":"Function","z":"Symbol"}"
    
  //JSON-unsafe object with circular reference on it
  var o = { },
    a = {
      b: 42,
      c: o,
      d: function(){}
    };

  // create a circular reference inside `a`
  o.e = a;

  // would throw an error on the circular reference
  // JSON.stringify( a );
  
  // define a custom JSON value serialization
  a.toJSON = function() {
    // only include the `b` property for serialization
    return { b: this.b };
  };

  JSON.stringify( a ); // "{"b":42}"
replacer (The replacer)

The replacer, as mentioned earlier, is a filter which indicates which properties are to be included in the JSON string. It can either be an array or a function. When an array, the replacer contains the string representations of only those properties which are to be included in the JSON string.

如前所述, replacer是一个过滤器,用于指示要在JSON字符串中包含哪些属性。 它可以是数组或函数。 当为数组时,替换器仅包含要包含在JSON字符串中的那些属性的字符串表示形式。

var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
  JSON.stringify(foo, ['week', 'month']);    // '{"week":45,"month":7}', only keep "week" and "month" properties

If replacer is a function, it will be called once for the object itself, and then once for each property in the object, and each time is passed two arguments, key and value. To skip a key in the serialization, undefined should be returned. Otherwise, the value provided should be returned. If any of these values are objects themselves, the replacer function serializes them recursively as well.

如果replacer是一个函数,它将对对象本身调用一次,然后对对象中的每个属性调用一次,并且每次传递两个参数keyvalue 。 要跳过序列化中的 ,应返回undefined 。 否则,应返回提供的 。 如果这些中的任何一个是对象本身,那么replacer函数也会递归地序列化它们。

function replacer(key, value) {
    // Filtering out properties
    if (typeof value === 'string') {
      return undefined;
    }
    return value;
  }

  var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
  JSON.stringify(foo, replacer);  // '{"week":45,"month":7}'

If an array is passed to JSON.stringify() and replacer returns undefined for any of its elements, the element’s value is replaced with null. replacer functions cannot remove values from an array.

如果将数组传递给JSON.stringify()并且replacer对其任何元素返回undefined ,则该元素的值将替换为nullreplacer函数无法从数组中删除值。

function replacer(key, value) {
    // Filtering out properties
    if (typeof value === 'string') {
      return undefined;
    }
    return value;
  }

  var foo = ['Mozilla', 'box', 45, 'car', 7];
  JSON.stringify(foo, replacer);  // "[null,null,45,null,7]"
space (The space)

The space parameter used for indentation makes the result of JSON.stringify() prettier.

用于缩进的space参数使JSON.stringify()的结果更漂亮。

var a = {
    b: 42,
    c: "42",
    d: [1,2,3]
  };

  JSON.stringify( a, null, 3 );
  // "{
  //    "b": 42,
  //    "c": "42",
  //    "d": [
  //       1,
  //       2,
  //       3
  //    ]
  // }"

  JSON.stringify( a, null, "-----" );
  // "{
  // -----"b": 42,
  // -----"c": "42",
  // -----"d": [
  // ----------1,
  // ----------2,
  // ----------3
  // -----]
  // }"

JSON解析 (JSON Parse)

The JSON.parse() method parses a string and construct a new object described by a string.

JSON.parse()方法解析字符串并构造一个由字符串描述的新对象。

句法: (Syntax:)

JSON.parse(text [, reviver])

参数: (Parameters:)

text The string to parse as JSON

text解析为JSON的字符串

reviver(Optional) The function will receive key and value as arguments. This function can be used to transform the result value.

reviver (可选)该函数将接收keyvalue作为参数。 此功能可用于转换结果值。

Here is an example on how to use JSON.parse():

这是有关如何使用JSON.parse()的示例:

var data = '{"foo": "bar"}';

console.log(data.foo); // This will print `undefined` since `data` is of type string and has no property named as `foo`

// You can use JSON.parse to create a new JSON object from the given string
var convertedData = JSON.parse(data);

console.log(convertedData.foo); // This will print `bar

Repl.it Demo

复制演示

Here is an example with reviver:

这是reviver的示例:

var data = '{"value": 5}';

var result = JSON.parse(data, function(key, value) {
    if (typeof value === 'number') {
        return value * 10;
    }
    return value;
});

// Original Data
console.log("Original Data:", data); // This will print Original Data: {"value": 5}
// Result after parsing
console.log("Parsed Result: ", result); // This will print Parsed Result:  { value: 50 }

In the above example, all numeric values are being multiplied by 10 - Repl.it Demo

在上面的例子中,所有的数字值被乘以10 - Repl.it演示

有关JSON的更多信息: (More info on JSON:)

翻译自: https://www.freecodecamp.org/news/json-stringify-method-explained/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值