PackageTop Level
Classpublic final class JSON
InheritanceJSON Inheritance Object

Language version: ActionScript 3.0
Runtime version: AIR 3.0

The JSON class lets applications import and export data using JavaScript Object Notation (JSON) format. JSON is an industry-standard data interchange format that is described at http://www.json.org.

As a rule, the ActionScript JSON class adheres to the ECMA-262 specification. The following exceptions occur where ActionScript provides greater flexibility than ECMAScript:

For most ActionScript classes, the ActionScript JSON.stringify() method generates a default encoding. ActionScript classes can change this encoding by defining a toJSON() method in the class or its prototype. For a few ActionScript classes, the default JSON encoding is inappropriate. These classes provide a trivial, overridable implementation of toJSON() that returns the value described in the following table. You can override or redefine the toJSON() methods on these classes if you require a specific behavior. The following table describes these exceptions:

ClassComments
ByteArrayOverridable toJSON() method returns the string "ByteArray".
DictionaryOverridable toJSON() method returns the string "Dictionary".
DateOverridable toJSON() method returns Date.toString(). This exception guarantees that the ActionScript Date constructor can parse the JSON string.
XMLOverridable toJSON() method returns the string "XML".

View the examples.



Public Properties
 PropertyDefined by
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
Public Methods
 MethodDefined by
 Inherited
Indicates whether an object has a specified property defined.
Object
 Inherited
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
  
parse(text:String, reviver:Function = null):Object
[static] Accepts a JSON-formatted String and returns an ActionScript Object that represents that value.
JSON
 Inherited
Indicates whether the specified property exists and is enumerable.
Object
 Inherited
Sets the availability of a dynamic property for loop operations.
Object
  
stringify(value:Object, replacer:* = null, space:* = null):String
[static] Returns a String, in JSON format, that represents an ActionScript value.
JSON
 Inherited
Returns the string representation of this object, formatted according to locale-specific conventions.
Object
 Inherited
Returns the string representation of the specified object.
Object
 Inherited
Returns the primitive value of the specified object.
Object
Method detail
parse()method
public static function parse(text:String, reviver:Function = null):Object

Language version: ActionScript 3.0
Runtime version: AIR 3.0

Accepts a JSON-formatted String and returns an ActionScript Object that represents that value. JSON objects, arrays, strings, numbers, Booleans, and null map to corresponding ActionScript values, as shown below:

JSON typeActionScript type
arrayArray
stringString
numberNumber
booleanBoolean
nullnull

The reviver parameter is a function that takes two parameters: a key and a value. You can use this function to transform or filter each key/value pair as it is parsed. If you supply a reviver function, your transformed or filtered value for each pair, rather than the default parsing, is returned in the parse() function output. If the reviver function returns undefined for any pair, the property is deleted from the final result.

When the argument passed to the reviver parameter is not a function, ActionScript throws a TypeError with error ID kJSONInvalidReviver. It also posts a localized error message.

If the parse() function encounters duplicate keys within an object, the duplicate key encountered last provides the value for all preceding occurrences of that key.

Parameters
text:String — The JSON string to be parsed
 
reviver:Function (default = null) — (Optional) A function that transforms each key/value pair that is parsed

Returns
Object
stringify()method 
public static function stringify(value:Object, replacer:* = null, space:* = null):String

Language version: ActionScript 3.0
Runtime version: AIR 3.0

Returns a String, in JSON format, that represents an ActionScript value. The stringify method can take three parameters.

The value parameter is required. This parameter is an ActionScript value. Typically, it is an Object or Array, but it can also be a String, Boolean, Number, or null.

The optional replacer parameter can be either a function or an array of strings or numbers. If it is a function, the function takes two parameters: a key and a value. You can use this function to transform or filter each key/value pair as it is parsed. If you supply a replacer function, your transformed or filtered value for each pair, rather than the default parsing, is returned in the parse() function output. If the replacer function returns undefined for any pair, the property is deleted from the final result. If replacer is an array, it is used as a filter for designating which properties are included in the output.

When the argument passed to the replacer parameter is neither an array or a function, ActionScript throws a TypeError with error ID kJSONInvalidReplacer. It also posts a localized error message.

The optional space parameter is a String or Number that allows white space to be injected into the returned string to improve human readability. Entries in generated JSON objects and JSON arrays are separated by a gap derived from the space parameter. This gap is always 0 to 10 characters wide. If space is a string, then the derived gap is the first ten characters of that string. If space is a non-negative number x, then the gap is x space characters, to a maximum of ten spaces. When the argument passed to the space parameter is not a String a Number, it is converted to a String for use as the gap in the output. Execution then proceeds.

When the stringify() method encounters a cyclic structure, it throws a TypeError with error ID kJSONCyclicStructure. It also posts a localized error message.

Parameters
value:Object — The ActionScript value to be converted into a JSON string
 
replacer:* (default = null) — (Optional) A function or an array that transforms or filters key/value pairs in the stringify output
 
space:* (default = null) — (Optional) A string or number that controls added white space in the returned String

Returns
String
Examples
examples\JSONExample
The following example uses the JSONExample class to show a JSON round-trip in ActionScript. This is accomplished with the following steps:
  1. The constructor for JSONExample assigns a string to the super-class's text member and initializes an internal counter.
  2. In addition, the class defines an array that can contain JSONExample objects that have been exported to JSON.
  3. JSONExample also defines a toJSON() method and a revive() method. The toJSON() method is called by JSON.stringify() to serialize JSONExample objects to JSON. The revive() method can be called from JSON.parse() methods to restore the full JSONExample object. This restoration is achieved by using a given ID to retrieve the original object from the revivable objects array.
  4. The script that uses the class definition creates an object that contains two TextField objects and one JSONExample object. It also creates a revivable objects array for storing TextField objects that have been exported to JSON.
  5. The replacer function of JSON.stringify() filters TextField objects out of the JSON string. In place of each removed object, replacer provides a marker with an ID that can be used later to retrieve the object. JSONExample objects, on the other hand, pass through according to their native JSON encoding.
  6. The reviver function of the parse() method recreates the original object by retrieving all referenced TextField and JSONExample objects.
 
 package {
	import flash.text.TextField;
	public class JSONExample extends TextField
	{
		static var nextId = 10000;
		static var revivable_objects:Array = [];
	    	public var id;

		public function JSONExample(s:String){
			super.text = s;
			id = ++nextId;
		}
		public function toJSON(k):*
		{
			// To be called internally by the JSON.stringify() method.
			// Save the original object internally.
			// Write out only a generated ID and the text value.
			revivable_objects[id] = this;
			return {"classJSONExample":{"reviveId":id,"contents":this.text}};
		}
		public static function revive(id:int):JSONExample
		{
			// For explicit use in the JSON.parse() method.
			// Revives the object using the ID obtained from the JSON string.
			return revivable_objects[id];
		}
	}
}

import flash.text.TextField;

var lastId = 20000;
var tf1:TextField = new TextField();
tf1.text = "Lorem ipsum";
var tf2:TextField = new TextField();
tf2.text = "Laughing cows";
var nt:JSONExample = new JSONExample("It was the best of times; it was the worst of times.");

var obj:Object = {a:tf1, b:nt, c:tf2};
var revivable_objects:Array = new Array();

var json_out = JSON.stringify(obj, function(k,v){
		if (v is JSONExample)
		{
			// Send JSONExample objects to the JSON output.
			// Note that stringify() calls JSONExample.toJSON() to serialize this object.
			return v;
		}
		if (v is TextField)
		{
			// Remove TextField objects from the JSON output.
			// Save the original object for reviving later.
			// Return a new object containing an identification marker
			// and the original object's revival ID.
			revivable_objects[++lastId] = v;
			return {"classTextField":{"reviveId":lastId}};
		}
		return v;
	}
);
			   
trace("json_out: " + json_out);

var json_in = JSON.parse(json_out, function(k,v) {
		if ("classTextField" in v) { // special marker tag from stringify() replacer code
			// Retrieve the original object based on the ID stored in the stringify() replacer function.
			var id = v["classTextField"].reviveId;
			return revivable_objects[id];
		} else if ("classJSONExample" in v){
			// Retrieve the original object based on the ID generated in JSONExample.toJSON().
			return JSONExample.revive(v["classJSONExample"].reviveId);
		}
		return v;
	}
);

if (json_in.a)
{
	if (json_in.a.hasOwnProperty("text"))
		{
			trace("json_in.a: " + json_in.a.text);
		}
}
if (json_in.b)
{
	if (json_in.b.hasOwnProperty("text"))
		{
			trace("json_in.b: " + json_in.b.text);
		}
}

if (json_in.c)
{
	if (json_in.c.hasOwnProperty("text"))
		{
			trace("json_in.c: " + json_in.c.text);
		}
}