1. 程式人生 > 其它 >JSON.stringify()

JSON.stringify()

技術標籤:Javascriptes6typescriptjavascript前端

// e8(相容模式),ie7和ie6沒有JSON物件
https://github.com/douglascrockford/JSON-js

JSON.stringify(value,replacer,space)

value : 將要轉為JSON字串的javascript物件。

replacer :該引數可以是多種型別,如果是一個函式,
 則它可以改變一個javascript物件在字串化過程中的行為,
 如果是一個包含 String 和 Number 物件的陣列,則它將作為一個白名單.
 只有那些鍵存在域該白名單中的鍵值對才會被包含進最終生成的JSON
字串中. 如果該引數值為null或者被省略,則所有的鍵值對都會被包含進最終生成的JSON字串中。 space :該引數可以是一個 String 或 Number 物件,作用是為了在輸出的JSON字串中插入空白符來增強可讀性. 如果是Number物件, 則表示用多少個空格來作為空白符; 最大可為10,大於10的數值也取10.最小可為1,小於1的數值無效,則不會顯示空白符. 如果是個 String物件, 則該字串本身會作為空白符,字串最長可為10個字元. 超過的話會擷取前十個字元. 如果該引數被省略 (或者為null), 則不會顯示空白符
const user = {
  id: 229
, name: 'John', email: '[email protected]' }; function replacer(key, value) { console.log(typeof value); if (key === 'email') { return undefined; // 替換函式可以用來過濾值,因為任何返回 undefined 的值將不在返回的字串中 } return value; } const userStr = JSON.stringify(user, replacer); // "{"id":229,"name":"John"}"
const students = [
    {
      name: 'akira',
      score: 100,
    }, {
      name: 'John',
      score: 60,
    }, {
      name: 'Jane',
      score: 90,
    }
  ];
  function replacer(key, value) {
    if (key === 'score') {
      if (value === 100) {
        return {
          score: value, // score 和 score 的key一樣,會導致堆疊溢位
          level: 'S'
        };
      } else if (value >= 90) {
        return {
          score: value,
          level: 'A'
        };
      } else if (value >= 70) {
        return {
          score: value,
          level: 'B'
        };
      } else if (value >= 50) {
        return {
          score: value,
          level: 'C'
        };
      } else {
        return {
          score: value,
          level: 'E'
        };
      }
    }
    return value;
  }
  textContent = JSON.stringify(students, replacer, 4);
// 返回的物件中依然還有score屬性,然後被函式遞迴地序列化,造成死迴圈,修改返回score key即可
const user = {
  name: 'John',
  email: '[email protected]',
  plan: 'Pro'
};
 
const userStr = JSON.stringify(user, null, '...');
// "{
// ..."name": "John",
// ..."email": "[email protected]",
// ..."plan": "Pro"
// }”

// 單取某個key 或 某一組key,第二個引數傳值key陣列
const userName = JSON.stringify(usser,['name']);

// "{"name": "John”}"
const data = {
  name: {
    name: 'aa',
    foo: 'bar',
  },
  foo: 'bar',
  other: {
    name: 'bb',
  },
}

const result = JSON.stringify(data, ["name"]);

console.log(result); // {name: {name: 'aa'}}
const obj = {
  foo: { bar: [11, 22, 33, 44], baz: { bing: true, boom: 'Hello' } } 
};
// The third parameter is the number of spaces used to 
// beautify the JSON output.
JSON.stringify(obj, null, 4); 
// =>"{
// =>    "foo": {
// =>        "bar": [
// =>            11,
// =>            22,
// =>            33,
// =>            44
// =>        ],
// =>        "baz": {
// =>            "bing": true,
// =>            "boom": "Hello"
// =>        }
// =>    }
// =>}"
一個被序列化的物件擁有 toJSON 方法,該 toJSON 方法就會覆蓋該物件預設的序列化行為
var obj = {
    foo: 'foo',
    toJSON:function(){
        return 'bar';
    }
  }
  JSON.stringify(obj);//'"bar"'
  JSON.stringify({x:obj});//'{"x":"bar”}'
  // 利用toJSON方法,可以修改物件轉換成JSON的預設行為。
 var censor = function(key,value){
    if(typeof(value) == 'function'){
        return Function.prototype.toString.call(value)
    }
    return value;
  }
  var foo = {bar:"1",baz:3,o:{name:'xiaoli',age:21,info:{sex:'男',getSex:function(){return 'sex';}}}};
  console.log(JSON.stringify(foo,censor,4))
// 結果為字串 
 {
    "bar": "1",
    "baz": 3,
    "o": {
        "name": "xiaoli",
        "age": 21,
        "info": {
            "sex": "男",
            "getSex": "function (){return 'sex';}"
        }
    }
  }