JSON.stringify()

來源:互聯網
上載者:User

標籤:

JSON.stringify()

在本文章中

概述

JSON.stringify() 方法可以將任意的 JavaScript 值序列化成 JSON 字串。

文法

JSON.stringify(value[, replacer [, space]])

參數

value

將要序列化成 JSON 字串的值。

replacer 可選

如果該參數是一個函數,則在序列化過程中,被序列化的值的每個屬性都會經過該函數的轉換和處理;如果該參數是一個數組,則只有包含在這個數組中的屬性名稱才會被序列化到最終的 JSON 字串中。關於該參數更詳細的解釋和樣本,請參考使用原生的 JSON 對象一文。

space 可選

指定縮排用的空白字串,用於美化輸出(pretty-print)。

描述

關於序列化,有下面五點注意事項:

  • 非數組對象的屬性不能保證以特定的順序出現在序列化後的字串中。
  • 布爾值、數字、字串的封裝對象在序列化過程中會自動轉換成對應的原始值。
  • undefined、任意的函數以及 symbol 值,在序列化過程中會被忽略(出現在非數組對象的屬性值中時)或者被轉換成 null(出現在數組中時)。
  • 所有以 symbol 為屬性鍵的屬性都會被完全忽略掉,即便 replacer 參數中強制指定包含了它們。
  • 不可枚舉的屬性會被忽略

JSON.stringify({});                        // ‘{}‘

JSON.stringify(true);                      // ‘true‘

JSON.stringify("foo");                     // ‘"foo"‘

JSON.stringify([1, "false", false]);       // ‘[1,"false",false]‘

JSON.stringify({ x: 5 });                  // ‘{"x":5}‘

 

JSON.stringify({x: 5, y: 6});             

// ‘{"x":5,"y":6}‘ 或者 ‘{"y":6,"x":5}‘ 都可能

JSON.stringify([new Number(1), new String("false"), new Boolean(false)]);

// ‘[1,"false",false]‘

JSON.stringify({x: undefined, y: Object, z: Symbol("")});

// ‘{}‘

JSON.stringify([undefined, Object, Symbol("")]);         

// ‘[null,null,null]‘

JSON.stringify({[Symbol("foo")]: "foo"});                

// ‘{}‘

JSON.stringify({[Symbol.for("foo")]: "foo"}, [Symbol.for("foo")]);

// ‘{}‘

JSON.stringify({[Symbol.for("foo")]: "foo"}, function (k, v) {

  if (typeof k === "symbol"){

    return "a symbol";

  }

});

 

// ‘{}‘ 

 

// 不可枚舉的屬性預設會被忽略:

JSON.stringify( Object.create(null, { x: { value: ‘x‘, enumerable: false }, y: { value: ‘y‘, enumerable: true } }) );

// ‘{"y":"y"}‘

space 參數

space 參數用來控制結果字串裡面的間距。如果是一個數字, 則在字串化時每一層級會比上一層級縮排多這個數字值的空格(最多10個空格);如果是一個字串,則每一層級會比上一層級多縮排用該字串(或該字串的前十個字元)。

JSON.stringify({ a: 2 }, null, " ");   // ‘{\n "a": 2\n}‘

使用定位字元(\t)來縮排:

JSON.stringify({ uno: 1, dos : 2 }, null, ‘\t‘)

// ‘{            \

//     "uno": 1, \

//     "dos": 2  \

// }‘

toJSON 方法

如果一個被序列化的對象擁有 toJSON 方法,那麼該 toJSON 方法就會覆蓋該對象預設的序列化行為:不是那個對象被序列化,而是調用 toJSON 方法後的傳回值會被序列化,例如:

var obj = {

  foo: ‘foo‘,

  toJSON: function () {

    return ‘bar‘;

  }

};

JSON.stringify(obj);      // ‘"bar"‘

JSON.stringify({x: obj}); // ‘{"x":"bar"}‘

使用 JSON.stringify 結合 localStorage 的例子

一些時候,你想儲存使用者建立的一個對象,並且,即使在瀏覽器被關閉後仍能恢複該對象。下面的例子是 JSON.stringify 適用於這種情形的一個樣板:

// 建立一個樣本資料

var session = {

    ‘screens‘ : [],

    ‘state‘ : true

};

session.screens.push({"name":"screenA", "width":450, "height":250});

session.screens.push({"name":"screenB", "width":650, "height":350});

session.screens.push({"name":"screenC", "width":750, "height":120});

session.screens.push({"name":"screenD", "width":250, "height":60});

session.screens.push({"name":"screenE", "width":390, "height":120});

session.screens.push({"name":"screenF", "width":1240, "height":650});

 

// 使用 JSON.stringify 轉換為 JSON 字串

// 然後使用 localStorage 儲存在 session 名稱裡

localStorage.setItem(‘session‘, JSON.stringify(session));

 

// 然後是如何轉換通過 JSON.stringify 產生的字串,該字串以 JSON 格式儲存在 localStorage 裡

var restoredSession = JSON.parse(localStorage.getItem(‘session‘));

 

// 現在 restoredSession 包含了儲存在 localStorage 裡的對象

console.log(restoredSession);

規範

正式名稱及連結

規範狀態

ECMAScript 5.1 (ECMA-262)
JSON.stringify

Standard

ECMAScript 2015 (6th Edition, ECMA-262)
JSON.stringify

Standard

瀏覽器安全色性

  • Desktop

 

  • Mobile

Feature

Chrome

Firefox (Gecko)

Internet Explorer

Opera

Safari

Basic support

(Yes)

3.5 (1.9.1)

8.0

10.5

4.0

相關連結

  • 使用原生的JSON 對象

 

JSON.stringify()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.