JSON.parse()与JSON.stringify()高级用法

前端之家收集整理的这篇文章主要介绍了JSON.parse()与JSON.stringify()高级用法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

    JSON.parse()与JSON.stringify是将JSON对象与字符串互相转换的方法,它们还有一些参数可以让我们在实际应用中更加方便,现在介绍一下它们的高级用法

    JSON.parse()

         JSON.parse(jsonString,(key,value) => {}) 可以接受两个参数,第一个就是我们已经熟悉的json字符串,第二个是一个回调函数,我们可以对返回的每一个value做处理,然后返回对应的value

const testJSON = { name: ‘test‘,value: 7,}; const jsonStr = JSON.stringify(testJSON); JSON.parse(jsonStr,value) => { if (typeof value === ‘string‘) { return value.toUpperCase(); } return value; }); // {
       name: ‘TEST‘,}

   JSON.stringify()

         JSON.stringify(jsonObject,replace,space) 可以接受三个参数,第一个是json对象,第二个在转成字符串前处理属性值,第三个在字符串中插入空白符增强可读性

    replace: 传入的参数可以是一个数组,也可以是一个回调函数,作用都是用于处理属性值;当是一个数组时,只有在数组中存在的属性,才会出现在最终转成的字符串中;当是一个回调函数时,可以处理每一个属性值,然后返回经过处理的值,若返回值是undefined ,则该属性值会被忽略,将不会出现在最终的字符串中。

   (注意: 当relace为数组,过滤属性时,嵌套属性同样会被过滤掉)   

const testJSON = { name: ‘test‘,cities: { shanghai: 1,},}; JSON.stringify(testJSON,[‘name‘]); // "{"name": ‘test‘}"
 JSON.stringify(testJSON,[‘name‘,‘cities‘]); // "{"name": ‘test‘,"cities": {}}"
 JSON.stringify(testJSON,‘cities‘,‘shanghai‘]); // "{"name": ‘test‘,"cities": {"shanghai": 1}}"
 JSON.stringify(testJSON,value) => { if (key === ‘cities‘) { return  ‘cities‘; } return value; }); // "{"name": ‘test‘,"cities": ‘cities‘}"
 JSON.stringify(testJSON,value) => { if (key === ‘shanghai‘) { return 9; } return value; }); // "{"name": ‘test‘,"cities": {"shanghai": 9}}"

   space: 传入的参数可以是String或Number的值,如果是String值,则该字符串会作为空白符,字符串最长可为10个字符,如果超过了10个字符,那么会截取前10个字符,若是undefined或null,则会被忽略,不会显示空白符;如果是Number的值,表示会有多少个空格作为空白符,最大数值为10,超过10也会被当做10来处理,最小为1,小于1则无效,不会显示空格

const testJSON = { name: ‘test‘,city: ‘shanghai‘,undefined,‘ ‘); // "{
       "name": ‘test‘,"city": ‘shanghai‘,}" JSON.stringify(testJSON,‘ ‘); // "{ "name": ‘test‘,‘\t‘); // "{ "name": ‘test‘,‘...‘); // "{ ..."name": ‘test‘,..."city": ‘shanghai‘,7); // "{ "name": ‘test‘,"city": ‘shanghai‘,// 缩进7个空格
     }"

    toJSON方法

       如果一个被序列化的json对象拥有toJSON方法,那么真正被序列化的值是toJSON方法返回的值,而不是本身的对象

const testJSON = { name: ‘test‘,toJSON: () => { return { toJson: ‘testJson‘ },}; JSON.stringify(testJSON); // "{"toJson": ‘testJson‘}"

  JSON.stringify()序列化复杂的json对象

     有的json对象中包含函数,那么序列化是会忽略掉函数,当我们想保留函数时,可以通过replace(回调函数)来处理

const testJSON = { name: ‘test‘,getName: () => { return ‘test‘; },}; JSON.stringify(kTextJson,value) => { if (typeof value === ‘function‘) { return Function.prototype.toString.call(value); } return value; },‘\t‘)); // {
      "name": "test","getName": "function getName() {\n    return ‘test‘;\n  }" }

  

     参考文章https://www.css88.com/archives/8735

猜你在找的Json相关文章