JSON常见操作

1.JSON---> 字符串:JSON.stringify(json)

看如下代码:

let json={"orderId":"E2018081400181122","prdId":34};
let toStr = JSON.stringify(json);
console.log(toStr)

返回结果如下:

2.字符串 ---> JSON:JSON.parse(str)

看如下代码:

let str='{"name":"Jack","age":10}';
let toJson = JSON.parse(str);
console.log(toJson);

返回结果如下:

注意:在字符串转化成JSON的时候,要遵守以下规则:

1.只能用双引号;
2.所有的名字必须用双引号包起来。

上面2条是JSON的标准写法,如果没有按这个来,在进行字符串转JSON的时候会报下面的错:

JSON的一些其他规则:

1.如果名字和值(key  和 value)一致时,可以只写一个。比如说

let numJson = {a:a,b:b}

你可以简写成

let numJson = {a,b}

2.里面有函数时,可以将":function"一块删掉。比如说:

let fcJson = {
    c:10,
    show:function(){
        return this.c
    },
}    

你可以简写成:

let fcJson = {
    c:10,
    show(){
        return this.c
    }
}

猜你喜欢

转载自www.cnblogs.com/sese/p/9501185.html