[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify [Back]  [Original]

JSON.stringify() - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

JSON.stringify()

20157

JSON.stringify() JavaScript JSON replacer replacer

console.log(JSON.stringify({ x: 5, y: 6 }));
// Expected output: '{"x":5,"y":6}'

console.log(
  JSON.stringify([new Number(3), new String("false"), new Boolean(false)]),
);
// Expected output: '[3,"false",false]'

console.log(JSON.stringify({ x: [10, undefined, function () {}, Symbol("")] }));
// Expected output: '{"x":[10,null,null,null]}'

console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)));
// Expected output: '"2006-01-02T15:04:05.000Z"'

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

value

JSON

replacer

JSON null

space

pretty-print 10 1 10 10 null

JSON

JSON.stringify() JSON

  • toJSON()
  • undefined symbol nullundefined undefinedJSON.stringify(function(){}) or JSON.stringify(undefined).
  • symbol replacer
  • Date toJSON() string Date.toISOString()
  • NaN Infinity null null
  • Map/Set/WeakMap/WeakSet

JSON.stringify

js
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}"

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";
  }
});

// undefined

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

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

replacer

replacer keyvalue

replacer key stringify

JSON value,

replacer values undefined null

(function)

function replacer(key, value) {
  if (typeof value === "string") {
    return undefined;
  }
  return value;
}

var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var jsonString = JSON.stringify(foo, replacer);

JSON {"week":45,"month":7}.

(array)

replacer JSON

JSON.stringify(foo, ['week', 'month']);
// '{"week":45,"month":7}', weekmonth

space

space 10 10

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

\t

js
JSON.stringify({ uno: 1, dos: 2 }, null, "\t");
// '{            \
//     "uno": 1, \
//     "dos": 2  \
// }'

toJSON

toJSON toJSON toJSON

js
var obj = {
  foo: "foo",
  toJSON: function () {
    return "bar";
  },
};
JSON.stringify(obj); // '"bar"'
JSON.stringify({ x: obj }); // '{"x":"bar"}'

JSON IETF TypeError

js
const circularReference = {};
circularReference.myself = circularReference;

//  "TypeError: cyclic object value" 
JSON.stringify(circularReference);

Douglas Crockford cycle.js

JSON.stringify() structuredClone()JavaScript API v8.serialize()

JSON.stringify JavaScript

JSON JavaScript JSON Line separator Paragraph separator JavaScript JSON JSONP

function jsFriendlyJSONStringify (s) {
    return JSON.stringify(s).
        replace(/\u2028/g, '\\u2028').
        replace(/\u2029/g, '\\u2029');
}

var s = {
    a: String.fromCharCode(0x2028),
    b: String.fromCharCode(0x2029)
};
try {
    eval('(' + JSON.stringify(s) + ')');
} catch (e) {
    console.log(e); // "SyntaxError: unterminated string literal"
}

// No need for a catch
eval('(' + jsFriendlyJSONStringify(s) + ')');

// console.log in Firefox unescapes the Unicode if
//   logged to console, so we use alert
alert(jsFriendlyJSONStringify(s)); // {"a":"\u2028","b":"\u2029"}

JSON.stringify localStorage

JSON.stringify

js
// 
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 2027 LanguageSpecification
# sec-json.stringify


Web Proxy Viewer  |  New URL  |  Original Page