Conversion between json string and json object in js

In the web front-end development process, the data transmission json is transmitted in the form of a string, while the js operation is a JSON object.

 

 

1. Convert JSON string to JSON object

 

var obj = JSON.parse (page [, 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 a function, returns after executing its method on the original value before being returned.

To parse the JSON string and return the corresponding value, an additional conversion function can be passed in, which is used to modify the generated value and its properties 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; // If you reach the top level, return the attribute value directly,
    return v * 2; // Otherwise double the property value.
});                            // { p: 10 }

JSON.parse('{"1": 1, "2": 2,"3": {"4": 4, "5": {"6": 6}}}', function (k, v) {
    console.log(k); // Output the current property name, so as to know that the traversal order is from the inside out,
                    // The last property name will be an empty string.
    return v; // Return the original property value, which is equivalent to not passing the reviver parameter.
});

// 1
// 2
// 4
// 6
// 5
// 3
// ""

  

 

Second, convert the JSON object into a JSON string.

 

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

 

value将要序列化成 一个JSON 字符串的值。

replacer 可选如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理。

space 可选指定缩进用的空白字符串,用于美化输出(pretty-print);如果参数是个数字,它代表有多少的空格;上限为10。该值若小于1,则意味着没有空格;如果该参数为字符串(字符串的前十个字母),该字符串将被作为空格;如果该参数没有提供(或者为null)将没有空格。
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

// Non-enumerable properties are ignored by default:
JSON.stringify(
    Object.create(
        null,
        {
            x: { value: 'x', enumerable: false },
            y: { value: 'y', enumerable: true }
        }
    )
);

// "{"y":"y"}"

  

如果replacer是一个数组,数组的值代表将被序列化成JSON字符串的属性名。

JSON.stringify(foo, ['week', 'month']);  
// '{"week":45,"month":7}', only keep the "week" and "month" property values.

  

 

 

Third, use JSON.stringify combined with localStorage local storage

 

Sometimes you want to store an object created by the user and restore the object even after the browser is closed. The following example is  JSON.stringify a boilerplate for this situation:

// create a sample data
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});

// Convert to JSON string using JSON.stringify
// Then use localStorage to save in the session name
localStorage.setItem('session', JSON.stringify(session));

// Then how to convert the string generated by JSON.stringify, which is saved in localStorage in JSON format
var restoredSession = JSON.parse(localStorage.getItem('session'));

// now restoredSession contains objects stored in localStorage
console.log(restoredSession);

  

 

4. Polyfill support for older versions below IE8

JSONObjects may not be supported by older browsers. The following code can be placed at the very beginning of the JS script, so that the object can be used in browsers that do not natively support JSON objects (such as IE6)  JSON.

JSONThe following algorithm is an imitation of a native object:

 

if (!window.JSON) {
  window.JSON = {
    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
    stringify: (function () {
      var toString = Object.prototype.toString;
      var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; };
      var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'};
      var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); };
      var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g;
      return function stringify(value) {
        if (value == null) {
          return 'null';
        } else if (typeof value === 'number') {
          return isFinite(value) ? value.toString() : 'null';
        } else if (typeof value === 'boolean') {
          return value.toString();
        } else if (typeof value === 'object') {
          if (typeof value.toJSON === 'function') {
            return stringify(value.toJSON());
          } else if (isArray(value)) {
            var res = '[';
            for (var i = 0; i < value.length; i++)
              res += (i ? ', ' : '') + stringify(value[i]);
            return res + ']';
          } else if (toString.call(value) === '[object Object]') {
            var tmp = [];
            for (var k in value) {
              if (value.hasOwnProperty(k))
                tmp.push(stringify(k) + ': ' + stringify(value[k]));
            }
            return '{' + tmp.join(', ') + '}';
          }
        }
        return '"' + value.toString().replace(escRE, escFunc) + '"';
      };
    })()
  };
}

  

 

You can also import 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});
  // => '{"Hello":123}'
  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>

  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324882334&siteId=291194637