Home  >  Article  >  Web Front-end  >  Implementation of methods for converting json strings and json objects into each other in js

Implementation of methods for converting json strings and json objects into each other in js

不言
不言Original
2018-07-20 14:53:141748browse

In the process of using js to develop, json strings and json objects need to be converted into each other. So how are json strings converted into json objects and json objects converted into json strings? Next, I will show you a specific example.

1. Convert JSON string to JSON object

var obj = JSON.parse(str[, reviver]);

Example:

JSON.parse('{}');              // {}
JSON.parse('true');            // true
JSON.parse('"foo"');           // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null');            // null
JSON.parse('1');               //  1

reviver: If it is a function, it returns after executing its method on the original value before being returned.

Parse the JSON string and return the corresponding value. You can pass in an additional conversion function to make certain modifications to the generated value and its attributes before returning it. The parameters k and v of the function represent the returned attribute name and attribute value respectively

JSON.parse('{"p": 5}', function (k, v) {
    if(k === '') return v;     // 如果到了最顶层,则直接返回属性值,
    return v * 2;              // 否则将属性值变为原来的 2 倍。
});                            // { p: 10 }
 
JSON.parse('{"1": 1, "2": 2,"3": {"4": 4, "5": {"6": 6}}}', function (k, v) {
    console.log(k); // 输出当前的属性名,从而得知遍历顺序是从内向外的,
                    // 最后一个属性名会是个空字符串。
    return v;       // 返回原始属性值,相当于没有传递 reviver 参数。
});
 
// 1
// 2
// 4
// 6
// 5
// 3
// ""

2. Convert the JSON object into a JSON string.

JSON.stringify(value[, replacer [, space]])

value will be serialized into a JSON string value.

replacer Optional If this parameter is a function, during the serialization process, each attribute of the serialized value will be converted and processed by the function.

space optionally specifies the blank string used for indentation, which is used to beautify the output (pretty-print); if the parameter is a number, it represents the number of spaces; the upper limit is 10. If the value is less than 1, it means there are no spaces; if the parameter is a string (the first ten letters of the string), the string will be treated as spaces; if the parameter is not provided (or is null) there will be no spaces. Example:

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({x: 5, y: 6});             
// "{"x":5,"y":6}"
 
JSON.stringify([new Number(1), new String("false"), new Boolean(false)]);
// '[1,"false",false]'
 
JSON.stringify({x: undefined, y: Object, z: Symbol("")});
// '{}'
 
JSON.stringify([undefined, Object, Symbol("")]);         
// '[null,null,null]'
 
JSON.stringify({[Symbol("foo")]: "foo"});                
// '{}'
 
JSON.stringify({[Symbol.for("foo")]: "foo"}, [Symbol.for("foo")]);
// '{}'
 
JSON.stringify(
    {[Symbol.for("foo")]: "foo"},
    function (k, v) {
        if (typeof k === "symbol"){
            return "a symbol";
        }
    }
);
 
 
// undefined
 
// 不可枚举的属性默认会被忽略:
JSON.stringify(
    Object.create(
        null,
        {
            x: { value: 'x', enumerable: false },
            y: { value: 'y', enumerable: true }
        }
    )
);
 
// "{"y":"y"}"

If replacer is an array, the value of the array represents the attribute name that will be serialized into a JSON string.

JSON.stringify(foo, ['week', 'month']); 
// '{"week":45,"month":7}', 只保留“week”和“month”属性值。

3. Use JSON.stringify combined with localStorage local storage

Sometimes, you want to store an object created by the user, and the object can still be restored even after the browser is closed. The following example is a template for JSON.stringify suitable for this situation:

// 创建一个示例数据
var session = {
    'screens' : [],
    'state' : true
};
session.screens.push({"name":"screenA", "width":450, "height":250});
session.screens.push({"name":"screenB", "width":650, "height":350});
session.screens.push({"name":"screenC", "width":750, "height":120});
session.screens.push({"name":"screenD", "width":250, "height":60});
session.screens.push({"name":"screenE", "width":390, "height":120});
session.screens.push({"name":"screenF", "width":1240, "height":650});
 
// 使用 JSON.stringify 转换为 JSON 字符串
// 然后使用 localStorage 保存在 session 名称里
localStorage.setItem('session', JSON.stringify(session));
 
// 然后是如何转换通过 JSON.stringify 生成的字符串,该字符串以 JSON 格式保存在 localStorage 里
var restoredSession = JSON.parse(localStorage.getItem('session'));
 
// 现在 restoredSession 包含了保存在 localStorage 里的对象
console.log(restoredSession);

4. Polyfill for support of older versions below IE8

JSON objects may not be supported by older versions of browsers . You can put the following code at the beginning of the JS script so that you can use JSON objects in browsers that do not natively support JSON objects (such as IE6).

The following algorithm is an imitation of the native JSON object:

You can also introduce the cdn of JSON3.js

<script src="//cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"></script>
<script>
  JSON.stringify({"Hello": 123});
  // => &#39;{"Hello":123}&#39;
  JSON.parse("[[1, 2, 3], 1, 2, 3, 4]", function (key, value) {
    if (typeof value == "number") {
      value = value % 2 ? "Odd" : "Even";
    }
    return value;
  });
  // => [["Odd", "Even", "Odd"], "Odd", "Even", "Odd", "Even"]
</script>

Related recommendations:

js Method analysis to convert json string to json object

The above is the detailed content of Implementation of methods for converting json strings and json objects into each other in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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