JAVASCRIPT
JSON Utilities
All samples are using Ink.requireModules
, please read how to use it at Ink.requireModules section
Use this class to convert JSON strings to JavaScript objects
.parse()
and also to do the opposite operation .stringify()
.
Internally, the standard JSON implementation is used if available
Otherwise, the functions mimic the standard implementation.
Here's how to produce JSON from an existing object:
Ink.requireModules(['Ink.Util.Json_1'], function (Json) {
var obj = {
key1: 'value1',
key2: 'value2',
keyArray: ['arrayValue1', 'arrayValue2', 'arrayValue3']
};
Json.stringify(obj); // The above object as a JSON string
});
And here is how to parse JSON:
Ink.requireModules(['Ink.Util.Json_1'], function (Json) {
var source = '{"key": "value", "array": [true, null, false]}';
Json.parse(source); // The above JSON string as an object
});
Function name | Description |
---|---|
.parse(text, reviver) | Parses a JSON text through a function |
.stringify(input, convertToUnicode) | Serializes a JSON object into a string. |
Parses a JSON text through a function
text
{String} Input stringreviver
{Function} Function receiving `(key, value)`, and `this`=(containing object), used to walk objects.Code
Ink.requireModules(['Ink.Util.Json_1'], function(InkJson) {
var jsonStr = '{"key": "value", "array": [true, null, false]}';
var obj = InkJson.parse(jsonStr);
Ink.log(obj);
// {
// key: 'value',
// array: [true, null, false]
// }
});
Using second argument
Code
Ink.requireModules(['Ink.Util.Json_1'], function(InkJson) {
var jsonStr = '{"a": "3", "numbers":false}';
var obj = InkJson.parse(jsonStr,function(key, value) {
if (!this.numbers && key === 'a') {
return "NO NUMBERS";
} else {
return value;
}
});
Ink.log(obj);
// {a: 'NO NUMBERS', numbers: false}
});
Serializes a JSON object into a string.
input
Data to be serialized into JSONconvertToUnicode
When `true`, converts string contents to unicode \uXXXXCode
Ink.requireModules(['Ink.Util.Json_1'], function(InkJson) {
var obj = {
key1: 'value1',
key2: 'value2',
keyArray: ['arrayValue1', 'arrayValue2', 'arrayValue3']
};
var jsonStr = InkJson.stringify(obj);
Ink.log(jsonStr);
// '{"key1":"value1","key2":"value2","keyArray":["arrayValue1","arrayValue2","arrayValue3"]}'
});