Core Function JsonEncode

From Sputnik Wiki
Jump to: navigation, search
JsonEncode( <value>, <options> )

Contents

Description

Returns the JSON representation of a value.

Parameters

value

The input string.

options

Optional; Bitmask consisting of any/all

@JSON_HEX_TAG            // All < and > are converted to \u003C and \u003E
@JSON_HEX_AMP            // All &s are converted to \u0026
@JSON_HEX_APOS           // All ' are converted to \u0027
@JSON_HEX_QUOT           // All " are converted to \u0022
@JSON_FORCE_OBJECT       // Outputs an object rather than an array
                         // when a non-associative array is used
                         // Especially useful when the recipient of the
                         // output is expecting an object and the array is empty
@JSON_NUMERIC_CHECK      // Encodes numeric strings as numbers
@JSON_BASE64_BINARY      // Encodes Binary in Base64
@JSON_CONSTRUCTOR_CLASS  // Encodes Classes in a Constructor so they will be decoded fully
                         // Note - This is ignored if you are using the JsonSerializable extend
@JSON_PRETTY_PRINT       // Use whitespace in returned data to format it so it is easy to read
@JSON_UNESCAPED_SLASHES  // Don't escape /
@JSON_UNESCAPED_UNICODE  // Encode multibyte Unicode characters literally (default is to escape as \uXXXX)

Default: 0 (All options False)

Return Value

Success: Returns a JSON encoded string on success or FALSE on failure.

Failure: Returns empty string.

Remarks

If you are decoding a JSON that contains a class with a constructor name and a class with that name cannot be located it will create an instance of IncompleteClass instead you can check for this by doing:

IsVarClass($a, 'IncompleteClass');

Example

Using @JSON_PRETTY_PRINT to make JSON easy to read

// Create something to encode
my $Testy = Pack("iz0", 1337, "Hi");
my $Hehe = array("One", "Two", $Testy, array("Cat" => array("Four", "Five"), "Dog"), "FoX");
// JSON Encode it
my $Encoded = JsonEncode($Hehe, @JSON_PRETTY_PRINT);
// Print the Encoded Text
say "Encoded:";
say $Encoded;
// Encoded:
// [
//   "One",
//   "Two",
//   "9\u0005\u0000\u0000Hi",
//   {
//     "0": "Dog",
//     "Cat": [
//       "Four",
//       "Five"
//     ]
//   },
//   "FoX"
// ]

Encode and Decode binary (Default method)

// Create a binary to encode
my $Testy = Pack("iz0", 1337, "Hi");
// JSON Encode it
my $Encoded = JsonEncode($Testy);
// Print the Encoded Text
say "Encoded:";
say $Encoded;
say;
// Decode the JSON
my $Decoded = JsonDecode($Encoded);
// Decode the output into binary by casting it
my $Bin = (binary)$Decoded;
// Print the Decoded binary
say "Decoded:";
printr (binary)$Bin;
// Prints:
// Encoded:
// "9\u0005\u0000\u0000Hi"
 
// Decoded:
// {BINARY:6}
// {
//         [0] => 57
//         [1] => 5
//         [2] => 0
//         [3] => 0
//         [4] => 72
//         [5] => 105
// }

Encode and Decode binary (Safest method)

// Create a binary to encode
my $Binary = Pack("iz0", 1337, "Hi");
// Hex encode the binary
my $Encoded = BinaryStr($Binary, '');
// Make an array to store some stuff
my $Arr = array("Hello", $Encoded, 100);
// JSON Encode it
my $Encoded = JsonEncode($Arr);
// Print the Encoded Text
say "Encoded:";
say $Encoded;
say;
// Decode the JSON
my $Decoded = JsonDecode($Encoded);
// Decode the binary in the array
$Decoded[1] = BinaryHex($Decoded[1]);
// Print the Decoded binary
say "Decoded:";
printr $Decoded;
// Prints:
// Encoded:
// ["Hello","390500004869",100]
// 
// Decoded:
// Array
// (
//     [0] => Hello
//     [1] => Binary
//         (
//             [0] => 57
//             [1] => 5
//             [2] => 0
//             [3] => 0
//             [4] => 72
//             [5] => 105
//         )
//     [2] => 100
// )

Encode and Decode binary (Base64 method: @JSON_BASE64_BINARY)

// Create a binary to encode
my $Testy = Pack("iz0", 1337, "Hi");
// JSON Encode it
my $Encoded = JsonEncode($Testy, @JSON_BASE64_BINARY);
// Print the Encoded Text
say "Encoded:";
say $Encoded;
say;
// Decode the JSON
my $Decoded = JsonDecode($Encoded);
// Decode the output into binary by casting it
my $Bin = (binary)$Decoded;
// Print the Decoded binary
say "Decoded:";
printr (binary)Decode64($Bin);
// Prints:
// Encoded:
// "OQUAAEhp"
 
// Decoded:
// {BINARY:6}
// {
//         [0] => 57
//         [1] => 5
//         [2] => 0
//         [3] => 0
//         [4] => 72
//         [5] => 105
// }

Encode and Decode an array

// Create an array to Json encode
my $Testy = array("Cat", "Dog", "Fox", 100, 200, 300);
// JSON Encode it
my $Encoded = JsonEncode($Testy);
// Print the Encoded Text
say "Encoded:";
say $Encoded;
say;
// Decode the JSON
my $Decoded = JsonDecode($Encoded);
// Print the Decoded object
say "Decoded:";
printr $Decoded;
// Prints:
// Encoded:
// ["Cat","Dog","Fox",100,200,300]
 
// Decoded:
// ARRAY
// {
//         [0] => Cat
//         [1] => Dog
//         [2] => Fox
//         [3] => 100
//         [4] => 200
//         [5] => 300
// }

Encode and Decode an associative array

// Create an array to Json encode
my $Testy = array("Cat" => "Meow", "Dog" => "Woof");
// JSON Encode it
my $Encoded = JsonEncode($Testy);
// Print the Encoded Text
say "Encoded:";
say $Encoded;
say;
// Decode the JSON
my $Decoded = JsonDecode($Encoded);
// Print the Decoded object
say "Decoded:";
printr $Decoded;
// Prints:
// Encoded:
// {"Cat":"Meow","Dog":"Woof"}
 
// Decoded:
// ARRAY
// {
//        [Cat] => Meow
//        [Dog] => Woof
// }

Encode and Decode a simple string

// Create the string to Json encode
my $Testy = array("Cat" => "Meow", "Dog" => "Woof");
// JSON Encode it
my $Encoded = JsonEncode("Hello");
// Print the Encoded Text
say "Encoded:";
say $Encoded;
say;
// Decode the JSON
my $Decoded = JsonDecode($Encoded);
// Print the Decoded object
say "Decoded:";
printr $Decoded;
// Prints:
// Encoded:
// "Hello"
 
// Decoded:
// Hello

Encode and Decode a class (using @JSON_CONSTRUCTOR_CLASS)

// The @JSON_CONSTRUCTOR_CLASS helps to recreate
// classes properly
 
// Create a base class
Class Testy
{
};
// Create an array to Json encode
my $Testy = new Testy();
// Add some variables to the class
$Testy->$Cat = "Meow";
$Testy->$Dog = "Woof";
$Testy->$Position = 1337;
// JSON Encode it
my $Encoded = JsonEncode($Testy, @JSON_CONSTRUCTOR_CLASS);
// Print the Encoded Text
say "Encoded:";
say $Encoded;
say;
// Decode the JSON
my $Decoded = JsonDecode($Encoded);
// Print the Decoded object
say "Decoded:";
printr $Decoded;
// Prints:
// Encoded:
// new testy({"cat":"Meow","dog":"Woof","position":1337})
 
// Decoded:
// {CLASS:testy;ID:5}
// {
//         [cat] => Meow
//         [dog] => Woof
//         [position] => 1337
// }

Encode and Decode a class (without using @JSON_CONSTRUCTOR_CLASS)

// Create a base class
Class Testy
{
};
// Create an array to Json encode
my $Testy = new Testy();
// Add some variables to the class
$Testy->$Cat = "Meow";
$Testy->$Dog = "Woof";
$Testy->$Position = 1337;
// JSON Encode it
my $Encoded = JsonEncode($Testy);
// Print the Encoded Text
say "Encoded:";
say $Encoded;
say;
// Decode the JSON
my $Decoded = JsonDecode($Encoded, @JSON_OBJECT_AS_ARRAY);
// Print the Decoded object
say "Decoded:";
// JSON returned an array so lets convert it
// into a class now
my $cls = NewClassFromArray("Testy", $Decoded);
printr $cls;
// Prints:
// Encoded:
// {"cat":"Meow","dog":"Woof","position":1337}
 
// Decoded:
// {CLASS:testy;ID:5}
// {
//         [cat] => Meow
//         [dog] => Woof
//         [position] => 1337
//         [this] =>       {CLASS:testy;ID:5}
// }

Encode and Decode a class (without using @JSON_CONSTRUCTOR_CLASS)

// Create a base class
Class Testy
{
};
// Create an array to Json encode
my $Testy = new Testy();
// Add some variables to the class
$Testy->$Cat = "Meow";
$Testy->$Dog = "Woof";
$Testy->$Position = 1337;
// JSON Encode it
my $Encoded = JsonEncode($Testy);
// Print the Encoded Text
say "Encoded:";
say $Encoded;
say;
// Decode the JSON
my $Decoded = JsonDecode($Encoded);
// Print the Decoded object
say "Decoded:";
// JSON returned an StdClass so lets convert it
// into a 'Testy' class now
my $cls = ConvertClass($Decoded, 'Testy');
// The conversion process returned a copy
// so lets dispose of the old StdClass one
unset($Decoded);
// Finally print the result
printr $cls;
// Prints:
// Encoded:
// {"cat":"Meow","dog":"Woof","position":1337}
 
// Decoded:
// {CLASS:testy;ID:5}
// {
//         [cat] => Meow
//         [dog] => Woof
//         [position] => 1337
//         [this] =>       {CLASS:testy;ID:5}
// }

Should Json Serializable

Class that add functions with the name ShouldJsonSerialize* (* = Variable name) can customize if JSON should enable that value or not with JsonEncode().

Examples
// Define a class that uses ShouldJsonSerialize
Class Testy
{
	my $Length;
	my $Position;
	// Create a function that decides if the
	// $Length variable should be JSON encoded or not
	// The function must start with:
	// ShouldJsonSerialize
	// and end with a variable name
	Function ShouldJsonSerializeLength()
	{
		return false;
	}
};
// Build new instance of the class
my $cls = new Testy();
$cls->$Length = 7;
$cls->$Position = 1;
// JSON Encode it
my $Encoded = JsonEncode($cls, @JSON_PRETTY_PRINT);
// Print the Encoded Text
say "Encoded:";
say $Encoded;
say;
my $Decoded = JsonDecode($Encoded);
// Print the Decoded
say "Decoded:";
printr $Decoded;
// Prints:
// Encoded:
// {
//   "position": 1
// }
 
// Decoded:
// ARRAY
// {
//         [position] => 1
// }

Json Serializable Classes

Classes using JsonSerializable can customize their JSON representation when encoded with JsonEncode().

Examples

A class that returns a number

// Define a class that uses JsonSerializable
Class Testy extends JsonSerializable
{
	my $value;
	Function __Construct($in)
	{
		$value = $in;
	}
	override Function JsonSerialize()
	{
		return $value;
	}
};
// JSON Encode it
my $Encoded = JsonEncode(new Testy(7), @JSON_PRETTY_PRINT);
// Print the Encoded Text
say "Encoded:";
say $Encoded;
say;
my $Decoded = JsonDecode($Encoded);
// Print the Decoded
say "Decoded:";
printr $Decoded;
// Prints:
// Encoded:
// 7
 
// Decoded:
// 7

A class that returns an array

// Define a class that uses JsonSerializable
Class Testy extends JsonSerializable
{
	my $value;
	Function __Construct()
	{
		$value = array();
	}
	override Function JsonSerialize()
	{
		return $value;
	}
};
// Build new instance of the class
my $cls = new Testy(7);
// Add stuff to the class
$cls->$value[] = "One";
$cls->$value[] = "Two";
$cls->$value[] = "Three";
// JSON Encode it
my $Encoded = JsonEncode($cls, @JSON_PRETTY_PRINT);
// Print the Encoded Text
say "Encoded:";
say $Encoded;
say;
my $Decoded = JsonDecode($Encoded);
// Print the Decoded
say "Decoded:";
printr $Decoded;
// Prints:
// Encoded:
// [
//   "One",
//   "Two",
//   "Three"
// ]
 
// Decoded:
// ARRAY
// {
//         [0] => One
//         [1] => Two
//         [2] => Three
// }
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox