【标准库】JSON

2019-03-04  本文已影响0人  南方帅

JSON 是JavaScript的原生对象,用来处理JSON格式数据,提供两个静态方法
JSON.stringify()JSON.parse()

["one", "two", "three"]

{ "one": 1, "two": 2, "three": 3 }

{"names": ["张三", "李四"] }

[ { "name": "张三"}, {"name": "李四"} ]
var user = {
  firstName: '三',
  lastName: '张',

  get fullName(){
    return this.lastName + this.firstName;
  },

  toJSON: function () {
    return {
      name: this.lastName + this.firstName
    };
  }
};

JSON.stringify(user)
// "{"name":"张三"}"
function f(key, value) {
  if (key === 'a') {
    return value + 10;
  }
  return value;
}

JSON.parse('{"a": 1, "b": 2}', f)
// {a: 11, b: 2}

判断一个字符串是不是JSON格式的字符串

    if (typeof str == 'string') {
        try {
            var obj=JSON.parse(str);
            if(typeof obj == 'object' && obj ){
                return true;
            }else{
                return false;
            }

        } catch(e) {
            console.log('error:'+str+'!!!'+e);
            return false;
        }
    }
    console.log('It is not a string!')
}

上一篇 下一篇

猜你喜欢

热点阅读