Module: UWA/Json


API for advanced JSON manipulation, convertion and fetching.




<static> UWA.Json.encode

Convert a value to JSON, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

Note: Alias to JSON.stringify native browser function.

UWA.Json.encode({})                  // '{}';
UWA.Json.encode(true)                // 'true';
UWA.Json.encode("foo")               // '"foo"';
UWA.Json.encode([1, "false", false]) // '[1,"false",false]';
UWA.Json.encode({ x: 5 })            // '{"x":5}';
UWA.Json.encode({x: 5, y: 6});       // '{"x":5,"y":6}' or '{"y":6,"x":5}'

<static> UWA.Json.decode

Parses a string as JSON and returns the parsed value.

Note: Alias to JSON.parse native browser function.

UWA.Json.decode('{}');               // {}
UWA.Json.decode('true');             // true
UWA.Json.decode('"foo"');            // "foo"
UWA.Json.decode('[1, 5, "false"]');  // [1, 5, "false"]
UWA.Json.decode('null');             // null

<static> UWA.Json.path

Apply and JSONPath query filter to a JSON Object.

var MyStore = {
   "store": {
       "book": [
           { "category": "reference",
             "author": "Nigel Rees",
             "title": "Sayings of the Century",
             "price": 8.95
           { "category": "fiction",
             "author": "Evelyn Waugh",
             "title": "Sword of Honour",
             "price": 12.99
           { "category": "fiction",
             "author": "Herman Melville",
             "title": "Moby Dick",
             "isbn": "0-553-21311-3",
             "price": 8.99
           { "category": "fiction",
             "author": "J. R. R. Tolkien",
             "title": "The Lord of the Rings",
             "isbn": "0-395-19395-8",
             "price": 22.99
       "bicycle": {
         "color": "red",
         "price": 19.95

UWA.Json.path(MyStore, "$");
// will return ["Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"]

UWA.Json.path(MyStore, "$", {
// will return [ "$['store']['book'][0]['author']", "$['store']['book'][1]['author']", ...]
More examples
XPath JSONPath Result
/store/book/author $[*].author the authors of all books in the store
//author $ all authors
/store/ * $.store.* all things in store, which are some books and a red bicycle.
/store//price $.store..price the price of everything in the store.
//book[3] $[2] the third book
//book[last()] $[(@.length-1)] OR $[-1:] the last book in order.
//book[position()<3] $[0,1] OR $[:2] the first two books
//book[isbn] $[?(@.isbn)] filter all books with isbn number
//book[price<10] $[?(@.price<10)] filter all books cheapier than 10
// * $..* all Elements in XML document. All members of JSON structure.
Detailed usage

JSONPath is a means of using XPath-like syntax to query JSON structures. It is not a standard, but it does offer a means of querying JavaScript structures directly without needing to convert to or from XML.

Here is a complete overview and a side by side comparison of the JSONPath syntax elements with its XPath counterparts.

XPath JSONPath Description
/ $ the root object/element
. @ the current object/element
/ . or [] child operator
// .. recursive descent. JSONPath borrows this syntax from E4X.
* - .* all objects/elements regardless their names.
n/a [start:end:step] array slice operator borrowed from ES4.
[] ?() applies a filter (script) expression.
n/a () script expression, using the underlying script engine.
.. n/a parent operator
() n/a grouping in Xpath
@ n/a attribute access. JSON structures don't have attributes.
[] [] subscript operator. XPath uses it to iterate over element collections and for predicates. In Javascript and JSON it is the native array operator.
pipe [,] Union operator in XPath results in a combination of node sets. JSONPath allows alternate names or array indices as a set.

XPath has a lot more to offer (Location pathes in not abbreviated syntax, operators and functions) than listed here. Moreover there is a remarkable difference how the subscript operator works in Xpath and JSONPath.

Square brackets in XPath expressions always operate on the node set resulting from the previous path fragment. Indices always start by 1. With JSONPath square brackets operate on the object or array addressed by the previous path fragment. Indices always start by 0.



<static> UWA.Json.prune(value, options) → {any}

Clone a value by converting it to be a safely JSON serializable value. Use this to convert unsupported value types to valid JSON types (null, string, number, array, object) and remove circular references.

var obj = {
    safe: 1,
    unsupported: /foo/

obj.circular = obj;

// will return the following object:
     safe: 1,
     unsupported: null,
     circular: null

UWA.Json.prune(obj, {
     fallback: function (o, reason) {
         if (, 'regexp')) {
             return String(o);
         if (reason === 'circular') {
             return { error: 'Circular reference' };
         return null;
// Will return the following object:
    safe: 1,
    unsupported: "/foo/",
    circular: {
        error: "Circular reference"
Name Type Argument Description
value any

The value to convert

options Object <optional>

a hash of options

Name Type Argument Description
toJSON function <optional>

a function called on each values, recursively. The value will be replaced by the result of the function in the resulting object. By default, this function is checking if a toJSON method exists and use it to get a serializable result. You normally don't need to change this (see the fallback option).

fallback function <optional>

a function called on each unserializable value. For now, values can't be serializable for two reasons:

  • it does not have a JSON type (ea: not a plain object, null, string, number nor boolean)

  • it is the reference of previous value (= circular reference)

The value is passed as first argument. The reason is passed as second argument (can be either "unsupported" or "circular"). By default, the fallback returns 'null', so all unserializable values are replaced by null.


the JSON-safe value


<static> UWA.Json.isJson(value) → {Bool}

Regular expression to test property values for being JSON.

UWA.Json.isJson('{}');     // true
UWA.Json.isJson('Hello');  // false
Name Type Description
value String

the string to test if it's valid JSON.


true is valid JSON else false.


<static> UWA.Json.xmlToJson(xml) → {Object}

Convert a XML String or Object into and Json Object.

   '<items title="titleAttribute">' +
   '   <item name="item1" foo="bar">item1TagValue</item>' +
   '   <item name="item2" foo="bar">item2TagValue</item>' +
   '   <label>label1TagValue</label>' +
   '   <label>label2TagValue</label>' +
   '   <title type="foo">titleTagValue</title>' +
// will return Object:
   "items": {
       "title": [
               "type": "foo",
               "nodeValue": "titleTagValue"
       "item": [
               "name": "item1",
               "foo": "bar",
               "nodeValue": "item1TagValue"
               "name": "item2",
               "foo": "bar",
               "nodeValue": "item2TagValue"
       "label": [
Name Type Description
xml String | Object

The XML source


The Object results from XML convertion into JSON.


<static> UWA.Json.request(url, options)

Creates a JSON request using script tag injection and handles the callbacks for you.

// Create a Callback
myWidget.parse = function (response) {
 // your parsing code

// Launch request
var myRequest = UWA.Json.request('', {
   onComplete: myModule.parse,
   data: {
       name: "Bob"

// Cancel Json request

// Will request url ""
// and expect has response "("Your data Json or Not")"
Name Type Description
url String

the URL of the data source

options Object

Settings object

Name Type Argument Default Description
onComplete Function

Callback receiving the Ajax response

onTimeout Function <optional>

Choose your own method

onFailure Function <optional>

Choose your own method

onCancel Function <optional>

Choose your own method

data Object <optional>

GET params as object

timeout Number <optional>

Set your request timeout in ms

async Boolean <optional>

Asynchronous request

callback Function <optional>

random (e.g jsonp123456789)

callbackMode Function <optional>

JsonP mode function or object

callbackName String <optional>

JsonP callback parameter name

useOfflineCache Boolean <optional>

enable Offline cache

useJsonpRequest Boolean <optional>

always use JsonP to do the request


Nothing, but if the request is successful, the callback method is fired and receives the content as parameter.


<static> UWA.Json.cleanRequest(jsonpId)

Remove JSONP tag script and callback function.

Name Type Description
jsonpId Object

The id of request callback