JavaScript JSON stringify() metod

Definition och användning

Metoden JSON.stringify() konverterar ett JavaScript-objekt till en sträng.

När data skickas till en webbserver måste data vara en sträng.

Exempel

Exempel 1

Stringify JavaScript object:

var obj = { "name":"Bill", "age":19, "city":"Seattle"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

Try it yourself

Example 2

Use a replacement function:

/* Replace the value of "city" with uppercase: */
var obj = { "name":"Bill", "age":"19", "city":"Seattle"};
var text = JSON.stringify(obj, function (key, value) {
  if (key == "city") {
    return value.toUpperCase();
  } else {
    return value;
  }
});

Try it yourself

Example 3

Usage space Parameter:

/* Insert 10 space characters for each space: */
var obj = { "name":"Bill", "age":"19", "city":"Seattle"};
var text = JSON.stringify(obj, null, 10);

Try it yourself

Example 4

Usage space Parameter:

/* Insert the word SPACE for each space: */
var obj = { "name":"Bill", "age":"19", "city":"Seattle"};
var text = JSON.stringify(obj, null, "SPACE");

Try it yourself

Syntax

JSON.stringify(obj, replacer, space)

Parameter value

Parameter Description
obj Required. The value to be converted to a string.
replacer

Optional. A function or array used to convert the result.

If the parameter is a function, during the serialization process, each property of the value to be serialized will be converted and processed by this function;

If the parameter is an array, only the property names contained in this array will be serialized into the final JSON string;

If the parameter is null or not provided, all properties of the object will be serialized.

space

Optional. A string or numeric value. Specifies the whitespace string used for indentation to improve the output (pretty-print).

If the parameter is a number, it represents how many spaces; the maximum is 10. If this value is less than 1, it means there are no spaces;

If the parameter is a string (when the string length exceeds 10 letters, take the first 10 letters), the string will be used as a space;

If the parameter is not provided (or is null), there will be no spaces.

Technical details

Return value: A String
JavaScript version: ECMAScript 5

Webbläsarstöd

Numreringen i tabellen anger den första webbläsaren som fullständigt stöder denna metod.

Metoder Chrome IE Firefox Safari Opera
stringify() 4.0 8.0 3.5 4.0 11.5

Relaterade sidor

JSON-lär:JSON sammanfattning