天天看点

JSON.parse() and JSON.stringify()

前言

最近发现一个比较好的关于前端的英文博文网站,主要是关于Javascript、Vuejs、React、Angular、CSS的前端网站博文网站,网站地址是:https://alligator.io/,感兴趣的可以看一下,跟着学习也不错。

本文翻译自JSON.parse() and JSON.stringify()

JSON对象,在所有的现代浏览器中是有效的,有两个非常有用的方法用于处理JSON格式的内容:parse和stringify。JSON.parse()接收一个JSON字符串作为参数,将它转换成一个JavaScript对象。JSON.stringify()接收一个Javascript对象作为参数,转换它为一个JSON字符串。

示例如下:

const myObj = {
  name: 'Skip',
  age: 2,
  favoriteFood: 'Steak'
};

const myObjStr = JSON.stringify(myObj);

console.log(myObjStr);
// "{"name":"Skip","age":2,"favoriteFood":"Steak"}"

console.log(JSON.parse(myObjStr));
// Object {name:"Skip",age:2,favoriteFood:"Steak"}           

复制

尽管这些方法通常用于对象,但它们也可以用于数组:

const myArr = ['bacon', 'letuce', 'tomatoes'];

const myArrStr = JSON.stringify(myArr);

console.log(myArrStr);
// "["bacon","letuce","tomatoes"]"

console.log(JSON.parse(myArrStr));
// ["bacon","letuce","tomatoes"]           

复制

—很抱歉打断这个程序! ?

您对学习React感兴趣吗? 如果是这样,我强烈建议您尝试Wes Bos的React初学者课程或Fullstack Advanced React&GraphQL课程。

考虑到当前使用COVID-19的情况,对于我们大多数人来说,时间很艰难,但是如果您呆在家里,则也许可以利用这些额外的时间来练习前端技能。 Wes将他所有课程的折扣都降低了50%,以帮助我们应对当前面临的挑战。

另外,这些是会员链接,因此,如果您购买课程,则可以帮助Alligator.io继续同时存在! ?

JSON.parse()

JSON.parse()可以为reviver函数使用第二个参数,该函数可以在返回对象值之前对其进行转换。 此处,对象的值在parse方法的返回对象中大写:

const user = {
  name: 'John',
  email: '[email protected]',
  plan: 'Pro'
};

const userStr = JSON.stringify(user);

JSON.parse(userStr, (key, value) => {
  if (typeof value === 'string') {
    return value.toUpperCase();
  }
  return value;
});           

复制

注意:尾部逗号在JSON中无效,因此,如果传递给它的字符串具有尾部逗号,则JSON.parse()抛出。

JSON.stringify()

JSON.stringify()可以接受两个附加参数,第一个是替换函数,第二个是String或Number值,用作返回的字符串中的空格。

replacer函数可用于滤除值,因为任何以undefined返回的值都将不在返回的字符串中:

const user = {
  id: 229,
  name: 'John',
  email: '[email protected]'
};

function replacer(key, value) {
  console.log(typeof value);
  if (key === 'email') {
    return undefined;
  }
  return value;
}

const userStr = JSON.stringify(user, replacer);
// "{"id":229,"name":"John"}"           

复制

并传入一个带有空格参数的示例:

const user = {
  name: 'John',
  email: '[email protected]',
  plan: 'Pro'
};

const userStr = JSON.stringify(user, null, '...');
// "{
// ..."name": "John",
// ..."email": "[email protected]",
// ..."plan": "Pro"
// }"           

复制

Beginner Javascript