Module: UWA/Json

UWA/Json

API for advanced JSON manipulation, convertion and fetching.

See:

Index

Members

<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.

Example
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.

Example
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.

Example
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, "$..author");
// will return ["Nigel Rees", "Evelyn Waugh", "Herman Melville", "J. R. R. Tolkien"]

UWA.Json.path(MyStore, "$..author", {
    resultType:"PATH"
});
// will return [ "$['store']['book'][0]['author']", "$['store']['book'][1]['author']", ...]
More examples
XPath JSONPath Result
/store/book/author $.store.book[*].author the authors of all books in the store
//author $..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] $..book[2] the third book
//book[last()] $..book[(@.length-1)] OR $..book[-1:] the last book in order.
//book[position()<3] $..book[0,1] OR $..book[:2] the first two books
//book[isbn] $..book[?(@.isbn)] filter all books with isbn number
//book[price<10] $..book[?(@.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.

See:

Methods

<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.

Example
var obj = {
    safe: 1,
    unsupported: /foo/
};

obj.circular = obj;

UWA.Json.prune(obj);
// will return the following object:
{
     safe: 1,
     unsupported: null,
     circular: null
}

UWA.Json.prune(obj, {
     fallback: function (o, reason) {
         if (UWA.is(o, '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"
    }
}
Parameters
Name Type Argument Description
value any

The value to convert

options Object <optional>

a hash of options

Properties
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.

Returns

the JSON-safe value

Type
any

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

Regular expression to test property values for being JSON.

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

the string to test if it's valid JSON.

Returns

true is valid JSON else false.

Type
Bool

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

Convert a XML String or Object into and Json Object.

Example
UWA.Json.xmlToJson(
   '<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>' +
   '</items>'
);
// will return Object:
{
   "items": {
       "title": [
           "titleAttribute",
           {
               "type": "foo",
               "nodeValue": "titleTagValue"
           }
       ],
       "item": [
           {
               "name": "item1",
               "foo": "bar",
               "nodeValue": "item1TagValue"
           },
           {
               "name": "item2",
               "foo": "bar",
               "nodeValue": "item2TagValue"
           }
       ],
       "label": [
           "label1TagValue",
           "label2TagValue"
       ]
   }
}
Parameters
Name Type Description
xml String | Object

The XML source

Returns

The Object results from XML convertion into JSON.

Type
Object

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

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

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

// Launch request
var myRequest = UWA.Json.request('http://example.org/api.php', {
   onComplete: myModule.parse,
   data: {
       name: "Bob"
   }
});

// Cancel Json request
myRequest.cancel();

// Will request url "http://example.org/api.php?callback=&name=Bob"
// and expect has response "("Your data Json or Not")"
Parameters
Name Type Description
url String

the URL of the data source

options Object

Settings object

Properties
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>
25000

Set your request timeout in ms

async Boolean <optional>
true

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>
false

enable Offline cache

useJsonpRequest Boolean <optional>
false

always use JsonP to do the request

Returns

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

See:

<static> UWA.Json.cleanRequest(jsonpId)

Remove JSONP tag script and callback function.

Parameters
Name Type Description
jsonpId Object

The id of request callback