UIZE JavaScript Framework

MODULES Uize.Json

1. Introduction

The Uize.Json module provides versatile methods for serializing and deserializing objects to and from the JSON (JavaScript Object Notation) format.

DEVELOPERS: Chris van Rensburg

The Uize.Json module provides versatile serializaton options to permit a wide array of results, from prettified JSON (with linebreaks, indentation, key sorting, etc.) to compact (efficient for AJAX communication).

1.1. Strict JSON Serialization

To allow you to serialize JavaScript objects in strict accordance with the JSON specification (to be found at json.org), the Uize.Json module provides convenient encoding presets for strict encoding.

1.1.1. Encoding Presets for Strict Encoding

The Uize.Json module provides two encoding presets for strict encoding - the strict encoding preset and the miniStrict encoding preset - both of which ensure that all object keys are quoted, and that both object keys and string values are quoted using double quotes.

1.1.1.1. The strict Encoding Preset

The 'strict' preset produces strict JSON serialization with pretty indentation and linebreaks.

EXAMPLE

Uize.Json.to (
  {
    prop1:true,
    prop2:'foo',
    prop3:42
  },
  'strict'
);

RESULT

{
  "prop1":true,
  "prop2":"foo",
  "prop3":42
}

1.1.1.2. The miniStrict Encoding Preset

The 'miniStrict' preset produces strict JSON serialization that is as compact as possible, with no linebreaks or indentation.

EXAMPLE

Uize.Json.to (
  {
    prop1:true,
    prop2:'foo',
    prop3:42
  },
  'miniStrict'
);

RESULT

{"prop1":true,"prop2":"foo","prop3":42}

1.1.2. Strict Serialization is Not the Default

If you don't specify the optional encoding parameter when calling the Uize.Json.to method, the encoding defaults to 'nice' - strict serialization is not the default.

Generally, when serializing values for debugging purposes, logging purposes, or as a part of build processes, it's more convenient to have your objects serialized in a neater and more readable form - without all the unnecessary and heavy double quotes around object keys. So, if you want strict JSON serialization, you must explicitly specify one of the two encoding presets for strict encoding.

1.1.2.1. When To Be Strict

Serializing a value to JSON using a strict encoding is appropriate when the serialized data is to be consumed by a JSON parser that only supports strict JSON syntax, such as a JSON parser provided for a server language like PHP.

1.1.2.2. When Not To Be Strict

Serializing a value to JSON using a non-strict encoding may be preferable when using the serialized data for debugging purposes, logging purposes, or as a part of build processes.

In such cases, strict JSON may be too heavy, ugly, or unnatural. For example, if you wanted to serialize some data and then plug the serialized data directly into some JavaScript module, you probably won't be wanting the forced quoting around object keys or the use of double quotes for quoting keys and string values - it's more traditional to use single quotes for quoting strings in JavaScript code.

1.2. Examples

The following example pages are good showcases for the Uize.Json module...

JSON Prettifier - Take ugly / unreadable JSON data and prettify it by re-serializing it. Make it look exactly how you want with the many serialization options provided.

SEARCH FOR EXAMPLES

Use the link below to search for example pages on the UIZE Web site that reference the Uize.Json module...

SEARCH

1.3. Implementation Info

The Uize.Json module defines the Uize.Json package under the Uize namespace.

1.3.1. Features Introduced in This Module

The features listed in this section have been introduced in this module.

STATIC METHODS

Uize.Json.from | Uize.Json.to

STATIC PROPERTIES

Uize.Json.encodingOptionsPresets | Uize.Json.moduleName | Uize.Json.pathToResources

1.3.2. Features Overridden in This Module

No features have been overridden in this module.

1.3.3. Features Inherited From Other Modules

This module has no inherited features.

1.3.4. Modules Directly Under This Namespace

1.3.5. Unit Tests

There is no dedicated unit tests module for the Uize.Json module.

2. Static Properties

2.1. Uize.Json.encodingOptionsPresets

2.1.1. Available Presets

2.1.1.1. Uize.Json.encodingOptionsPresets.mini

This encoding options preset can be used to serialize values to the most compact non-strict JSON form.

This encoding preset is useful when serializing objects that are to be stored in string form somewhere, or that are to be sent "over the wire". The mini preset will minimize storage space needed to store serialized objects and bandwidth needed to send serialized objects over a network. The mini preset minimizes size by serializing objects without using any whitespace - no linebreaks, indentation, or key padding.

EXAMPLE

{foo:'bar',hello:'world',subObject:{foo:'bar'}}

The Uize.Json.encodingOptionsPresets.mini preset defines the following encoding options...

SETTINGS

{
  indentChars:'',
  keyAlign:'left',
  keyDelimiter:':',
  linebreakChars:'',
  padKeys:false,
  quoteChar:'\'',
  sortKeys:false,
  whenToQuoteKeys:'auto'
}

2.1.1.2. Uize.Json.encodingOptionsPresets.miniStrict

This encoding options preset can be used to serialize values to the most compact strict JSON form.

This encoding preset is useful when you want all the benefits of the Uize.Json.encodingOptionsPresets.mini preset, but where you also need objects to be serialized using strict JSON serialization (possibly because some parts of the system only support deserializing objects that are in strict JSON form).

EXAMPLE

{"foo":"bar","hello":"world","subObject":{"foo":"bar"}}

The Uize.Json.encodingOptionsPresets.miniStrict preset defines the following encoding options...

SETTINGS

{
  indentChars:'',
  keyAlign:'left',
  keyDelimiter:':',
  linebreakChars:'',
  padKeys:false,
  quoteChar:'"',
  sortKeys:false,
  whenToQuoteKeys:'always'
}

2.1.1.3. Uize.Json.encodingOptionsPresets.nice

This encoding options preset can be used to serialize values to a human readable non-strict JSON form.

This encoding preset is useful when serializing objects that are to be displayed (possibly for debugging or troubleshooting purposes), or that are to be incorporated into files that should be human readable (possibly as part of a build process). The nice preset spreads object properties over multiple lines and indents lines to indicate hierarchical structure.

EXAMPLE

{
  foo:'bar',
  hello:'world',
  subObject:{
    foo:'bar'
  }
}

The Uize.Json.encodingOptionsPresets.nice preset defines the following encoding options...

SETTINGS

{
  indentChars:'\t',
  keyAlign:'left',
  keyDelimiter:':',
  linebreakChars:'\n',
  padKeys:false,
  quoteChar:'\'',
  sortKeys:false,
  whenToQuoteKeys:'auto'
}

2.1.1.4. Uize.Json.encodingOptionsPresets.strict

This encoding options preset can be used to serialize values to a human readable strict JSON form.

This encoding preset is useful when you want all the benefits of the Uize.Json.encodingOptionsPresets.nice preset, but where you also need objects to be serialized using strict JSON serialization (possibly because some parts of the system only support deserializing objects that are in strict JSON form).

EXAMPLE

{
  "foo":"bar",
  "hello":"world",
  "subObject":{
    "foo":"bar"
  }
}

The Uize.Json.encodingOptionsPresets.strict preset defines the following encoding options...

SETTINGS

{
  indentChars:'\t',
  keyAlign:'left',
  keyDelimiter:':',
  linebreakChars:'\n',
  padKeys:false,
  quoteChar:'"',
  sortKeys:false,
  whenToQuoteKeys:'always'
}

IMPLEMENTATION INFO

this feature was introduced in this module

2.2. Uize.Json.moduleName

IMPLEMENTATION INFO

this feature was introduced in this module

2.3. Uize.Json.pathToResources

IMPLEMENTATION INFO

this feature was introduced in this module

3. Static Methods

3.1. Uize.Json.from

Returns a value of any type, being the result of evaluating the expression specified by the jsonSTR parameter.

SYNTAX

valueANYTYPE = Uize.Json.from (jsonSTR);

NOTES

see the companion Uize.Json.to static method

IMPLEMENTATION INFO

this feature was introduced in this module

3.2. Uize.Json.to

Serializes the specified value to a string of JSON format. The value to serialize can be a string, boolean, number, object, array, null, undefined, or a regular expression.

SYNTAX

jsonSTR = Uize.Json.to (valueANYTYPE);

VARIATION 1

jsonSTR = Uize.Json.to (valueANYTYPE,serializationOptionsOBJ);

When the optional serializationOptionsOBJ parameter is specified, then the way in which the value is serialized to JSON format can be configured to produce wide ranging results, from prettified to compact. The value of the serializationOptionsOBJ parameter should be an object, with properties as follows...

SERIALIZATION OPTIONS

{
  indentChars:indentCharsSTR,         // optional, defaults to one tab
  linebreakChars:linebreakCharsSTR,   // optional, defaults to one linebreak
  quoteChar:quoteCharSTR,             // optional, defaults to a single quote
  keyDelimiter:keyDelimiterSTR,       // optional, defaults to colon without spaces
  padKeys:padKeysBOOL,                // optional, defaults to false
  keyAlign:keyAlignSTR,               // 'left' (default) | 'center' | 'right'
  whenToQuoteKeys:whenToQuoteKeysSTR, // 'auto' (default) | 'auto all' | 'always'
  sortKeys:sortKeysBOOL               // optional, defaults to false
}

3.2.1. indentChars

A string, specifying the characters that should be used to indent key/value pairs of objects and elements of arrays. Defaults to one tab. Specify an empty string for compact serialization.

3.2.2. linebreakChars

A string, specifying the characters to be used to separate key/value pairs of objects and elements of arrays. Defaults to a single linebreak. Specify an empty string for compact serialization.

3.2.3. quoteChar

A string, specifying the character to be used when quoting string literals for string values or object property names (keys) that require quoting. Defaults to a single quote character.

3.2.4. keyDelimiter

A string, specifying the characters to be used when separating keys from values for serializing objects. Defaults to a colon without padding spaces around it. Add your own spaces to order.

3.2.5. padKeys

A boolean, specifying whether or not keys should be padded with spaces so that all keys occupy the same number of characters and so that the keyDelimiter character lines up vertically. Defaults to false. See the companion keyAlign property.

3.2.6. keyAlign

A string, specifying whether the keys should be aligned left, center, or right when padding keys. Only applicable when the companion padKeys property is set to true.

3.2.7. whenToQuoteKeys

A string, specifying under what conditions object property names (keys) should be quoted. The default value of 'auto' causes individual keys to only be quoted when necessary. The value of 'auto all' causes all keys of the same object to be quoted if any of the keys needs to be quoted. The value of 'always' causes all keys to always be quoted.

3.2.8. sortKeys

A boolean, specifying whether or not object property names (keys) should be sorted ASCIIbetically when serializing objects. Defaults to false.

EXAMPLES

For the following examples, let's assume that we have a JavaScript object defined as follows...

var myObject = {
  someNumber:123.456,
  aBoolean:true,
  'value is a regular expression':/\d+/gim,
  123.456:'it\'s a floating point key!',
  '~!@#$%^&*()_+':1,
  'a key with a double quote "':1,
  'a key with a single quote \'':1
};

EXAMPLE 1

The following call to Uize.Json.to...

Uize.Json.to (myObject,{keyDelimiter:' : '});

...would produce the output...

{
  someNumber : 123.456,
  aBoolean : true,
  'value is a regular expression' : /\d+/gim,
  123.456 : 'it\'s a floating point key!',
  '~!@#$%^&*()_+' : 1,
  'a key with a double quote "' : 1,
  'a key with a single quote \'' : 1
}

EXAMPLE 2

The following call to Uize.Json.to...

Uize.Json.to (myObject,{keyDelimiter:' : ',padKeys:true,keyAlign:'left'});

...would produce the output...

{
  someNumber                      : 123.456,
  aBoolean                        : true,
  'value is a regular expression' : /\d+/gim,
  123.456                         : 'it\'s a floating point key!',
  '~!@#$%^&*()_+'                 : 1,
  'a key with a double quote "'   : 1,
  'a key with a single quote \''  : 1
}

EXAMPLE 3

The following call to Uize.Json.to...

Uize.Json.to (myObject,{keyDelimiter:' : ',padKeys:true,keyAlign:'right'});

...would produce the output...

{
                       someNumber : 123.456,
                         aBoolean : true,
  'value is a regular expression' : /\d+/gim,
                          123.456 : 'it\'s a floating point key!',
                  '~!@#$%^&*()_+' : 1,
    'a key with a double quote "' : 1,
   'a key with a single quote \'' : 1
}

EXAMPLE 4

The following call to Uize.Json.to...

Uize.Json.to (myObject,{keyDelimiter:' : ',whenToQuoteKeys:'auto all'});

...would produce the output...

{
  'someNumber' : 123.456,
  'aBoolean' : true,
  'value is a regular expression' : /\d+/gim,
  '123.456' : 'it\'s a floating point key!',
  '~!@#$%^&*()_+' : 1,
  'a key with a double quote "' : 1,
  'a key with a single quote \'' : 1
}

EXAMPLE 5

The following call to Uize.Json.to...

Uize.Json.to (myObject,{keyDelimiter:' : ',quoteChar:'"'});

...would produce the output...

{
  someNumber : 123.456,
  aBoolean : true,
  "value is a regular expression" : /\d+/gim,
  123.456 : "it's a floating point key!",
  "~!@#$%^&*()_+" : 1,
  "a key with a double quote \"" : 1,
  "a key with a single quote '" : 1
}

EXAMPLE 6

The following call to Uize.Json.to...

Uize.Json.to (myObject,{keyDelimiter:' : ',sortKeys:true});

...would produce the output...

{
  123.456 : 'it\'s a floating point key!',
  'a key with a double quote "' : 1,
  'a key with a single quote \'' : 1,
  aBoolean : true,
  someNumber : 123.456,
  'value is a regular expression' : /\d+/gim,
  '~!@#$%^&*()_+' : 1
}

VARIATION 2

jsonSTR = Uize.Json.to (valueANYTYPE,'mini');

When the special string value 'mini' is specified in place of the serializationOptionsOBJ parameter, then serialization options are used that will produce a compact serialization of the specified value. This is equivalent to specifying the value {indentChars:'',linebreakChars:''} for the serializationOptionsOBJ parameter.

NOTES

see the companion Uize.Json.from static method

IMPLEMENTATION INFO

this feature was introduced in this module