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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章