共用方式為


JSON.stringify Method (Windows Scripting - JScript)

 

Serializes a JScript value into JavaScript Object Notation (JSON) text.

Syntax

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

Arguments

  • value
    Required. A JScript value, usually an object or array, to be serialized.

  • replacer
    Optional. A function or array that filters and transforms the results.

    If replacer is a function, JSON.stringify calls the function, passing in the key and value of each member. The return value is serialized instead of the original value. If the function returns undefined, the member will be excluded from the serialization. The key for the root object is an empty string: "".

    If replacer is an array, only members with key values in the array will be serialized. The order of serialization is the same as the order of the keys in the array. The replacer array is ignored when the value argument is also an array.

  • space
    Optional. Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.

    If space is omitted, the return-value text is generated without any extra white space.

    If space is a number, the return-value text is indented with the specified number of white spaces at each level. If space is larger than 10, text is indented 10 spaces.

    If space is a non-empty string, such as '\t', the return-value text is indented with the characters in the string at each level.

    If space is a string that is longer than 10 characters, the first 10 characters are used.

Return Value

A string that contains the serialized JSON text.

Exceptions

Exception

Condition

Exception

Condition

Invalid replacer argument

The replacer argument is not a function or an array.

Circular reference in value argument not supported

The value argument contains a circular reference.

Remarks

If the value that is being serialized has a toJSON method, the JSON.stringify method calls the toJSON method and uses the return value for serialization. If the return value of the toJSON method is undefined, the member will not be serialized. This enables an object to determine its own JSON representation.

Values that do not have JSON representations, such as undefined, will not be serialized. In objects, they will be dropped. In arrays, they will be replaced with null.

String values begin and end with a quotation mark. All Unicode characters may be enclosed in the quotation marks except for the characters that must be escaped by using a backslash. The following characters must be preceded by a backslash:

  • Quotation mark (")

  • Backslash (\)

  • Backspace (b)

  • Formfeed (f)

  • Newline (n)

  • Carriage return (r)

  • Horizontal tab (t)

  • Four-hexadecimal-digits (uhhhh)

Order of Execution

During the serialization process, if a toJSON method exists for the value argument, JSON.stringify first calls the toJSON method. If it does not exist, the original value is used. Next, if a replacer argument is provided, the value (original value or toJSON return-value) is replaced with the return-value of the replacer argument. Finally, white spaces are added to the value based on the optional space argument to generate the final serialized JSON text.

This example uses JSON.stringify to serialize the contact object to JSON text. The memberfilter array is defined so that only the surname and phone members are serialized. The firstname member is omitted.

var contact = new Object();
contact.firstname = "Jesper";
contact.surname = "Aaberg";
contact.phone = ["555-0100", "555-0120"];

var memberfilter = new Array();
memberfilter[0] = "surname";
memberfilter[1] = "phone";
var jsonText = JSON.stringify(contact, memberfilter, "\t");
/* the value of jsonText is
'{
    "surname": "Aaberg",
    "phone": [
        "555-0100",
        "555-0120"
    ]
}'
*/

This example uses JSON.stringify to serialize an array. The replaceToUpper function converts every string in the array to uppercase.

var continents = new Array();
continents[0] = "Europe";
continents[1] = "Asia";
continents[2] = "Australia";
continents[3] = "Antarctica";
continents[4] = "North America";
continents[5] = "South America";
continents[6] = "Africa";

var jsonText = JSON.stringify(continents, replaceToUpper);
/* the value of jsonText is:
'"EUROPE,ASIA,AUSTRALIA,ANTARCTICA,NORTH AMERICA,SOUTH AMERICA,AFRICA"'
*/

function replaceToUpper(key, value) {
    return value.toString().toUpperCase();
}

This example uses the toJSON method to serialize string member values in uppercase.

var contact = new Object();
contact.firstname = "Jesper";
contact.surname = "Aaberg";
contact.phone = ["555-0100", "555-0120"];

contact.toJSON = function(key)
 {
    var replacement = new Object();
    for (var val in this)
    {
        if (typeof (this[val]) === 'string')
            replacement[val] = this[val].toUpperCase();
        else
            replacement[val] = this[val]
    }
    return replacement;
};

var jsonText = JSON.stringify(contact);

/* The value of jsonText is:
'{"firstname":"JESPER","surname":"AABERG","phone":["555-0100","555-0120"]}'
*/

Requirements

Version 5.8

Note

Starting with JScript 5.8, by default, the JScript scripting engine supports the language feature set as it existed in version 5.7. This is to maintain compatibility with the earlier versions of the engine. To use the complete language feature set of version 5.8, the Windows Script interface host has to invoke IActiveScriptProperty::SetProperty.

Internet Explorer 8 opts into the JScript 5.8 language features when the document mode for Internet Explorer 8 is "Internet Explorer 8 Standards" mode. For other document modes, Internet Explorer uses the version 5.7 feature set.

JScript 5.8 includes native JavaScript Object Notation (JSON) support and the accessor methods for Document Object Model (DOM) prototypes.

Internet Explorer 8 Release Changes

After the initial release of Internet Explorer 8, an update was made to the JSON feature. The update improved JSON interoperability in conformance with the ECMAScript 5 standard. The update applies to Internet Explorer 8. For more information about the update, see KB976662.

The following table summarizes changes to the JSON.stringify method. Most of the changes apply to invalid argument values or to other irregular situations.

Condition

Previous behavior

New behavior

Examples

value is not supplied, or is a non-serializable object, such as an empty object or a host object.

Returns the string value "undefined".

Returns the undefined value.

JSON.stringify()

JSON.stringify(Number)

JSON.stringify(window)

JSON.stringify(undefined)

JSON.stringify(function theFunc() {})

value is a cyclic object value.

When the exception is thrown, the value of name property of the Error object is "Error".

When the exception is thrown, the value of name property of the Error object is "TypeError".

var obj = {prop:1};

obj.circRefProp = obj;

JSON.stringify(obj);

var arr = [];

arr[0] = arr;

JSON.stringify(arr);

value is an empty DOM (Document Object Model) form value.

Returns the string value "null".

Returns the empty string value.

JSON.stringify(document.getElementById("EmptyInputBox"))

replacer is a function that returns a String or Number object.

Returns an object that has no properties.

Returns correct values.

function replacer(key, value) {

switch (key) {

case "a":

return new String("A");

case "b":

return new Number(10);

case "c":

return "C";

default:

return value;

}

}

 

var obj = { "a": 1,  "b": 2,  "c": 3 };

JSON.stringify(obj, replacer);

replacer is not callable.

Throws a TypeError exception containing the message "Invalid replacer argument".

Ignores the argument.

var obj = new Object();

obj.boolProp = true;

var replacer = true;

JSON.stringify(obj, replacer);

space is an empty string.

Adds a new line.

Adds a single space.

space is a number larger than 10.

Adds the specified number of spaces.

Adds 10 spaces.

space is a string that is longer than 10 characters.

Uses all of the specified characters.

Uses the first 10 characters.

space is a String or Number object.

Ignores the argument.

Converts the object to a primitive string or number value.

space is a non-integer number value.

Truncates the argument to an integer.

Rounds the argument to an integer.

Change History

Date

History

Reason

February 2010

Added information about Internet Explorer 8 release changes.

Information enhancement.

September 2009

Fixed output value comments in examples.

Content bug fix.

August 2008

Added topic.

Information enhancement.

See Also

JSON.parse Method
toJSON Method
JSON Object
JScript Methods