JavaScript JSON stringify() metoden
- Forrige side parse()
- Næste side parse()
- Gå tilbage til niveauet over JavaScript JSON Reference Håndbog
Definisjon og bruk
JSON.stringify() metoden konverterer et JavaScript-objekt til en streng.
Når data sendes til en webserver, skal dataene være streng.
Eksempel
Eksempel 1
Stringify JavaScript object:
var obj = { "name":"Bill", "age":19, "city":"Seattle"}; var myJSON = JSON.stringify(obj); document.getElementById("demo").innerHTML = myJSON;
Example 2
Use a replacement function:
/* Replace the "city" value 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; } });
Example 3
Usage space Parameters:
/* Insert 10 spaces for each space:*/ var obj = { "name":"Bill", "age":"19", "city":"Seattle"}; var text = JSON.stringify(obj, null, 10);
Example 4
Usage space Parameters:
/* Insert the word SPACE for each space:*/ var obj = { "name":"Bill", "age":"19", "city":"Seattle"}; var text = JSON.stringify(obj, null, "SPACE");
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 for converting 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. Specify a space string for indentation to beautify 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 |
Browserstøtte
Tal i tabellen angiver den første browserversion, der fuldt ud understøtter denne metode.
Metoder | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
stringify() | 4.0 | 8.0 | 3.5 | 4.0 | 11.5 |
Relaterede sider
JSON tutorial:JSON introduktion
- Forrige side parse()
- Næste side parse()
- Gå tilbage til niveauet over JavaScript JSON Reference Håndbog