dataschema-json-debug.js revision 10d8bafc5c24f3a4285cf6060a1935ba5cfc4b85
18N/AYUI.add('dataschema-json', function(Y) {
18N/A
18N/A/**
18N/AProvides a DataSchema implementation which can be used to work with JSON data.
18N/A
18N/A@module dataschema
18N/A@submodule dataschema-json
18N/A**/
18N/A
18N/A/**
18N/AProvides a DataSchema implementation which can be used to work with JSON data.
18N/A
18N/ASee the `apply` method for usage.
18N/A
18N/A@class DataSchema.JSON
18N/A@extends DataSchema.Base
18N/A@static
18N/A**/
18N/Avar LANG = Y.Lang,
18N/A isFunction = LANG.isFunction,
18N/A isObject = LANG.isObject,
58N/A isArray = LANG.isArray,
18N/A // TODO: I don't think the calls to Base.* need to be done via Base since
18N/A // Base is mixed into SchemaJSON. Investigate for later.
18N/A Base = Y.DataSchema.Base,
18N/A
18N/A SchemaJSON;
18N/A
18N/ASchemaJSON = {
18N/A
18N/A/////////////////////////////////////////////////////////////////////////////
18N/A//
42N/A// DataSchema.JSON static methods
42N/A//
18N/A/////////////////////////////////////////////////////////////////////////////
18N/A /**
18N/A * Utility function converts JSON locator strings into walkable paths
18N/A *
18N/A * @method getPath
18N/A * @param locator {String} JSON value locator.
18N/A * @return {String[]} Walkable path to data value.
18N/A * @static
18N/A */
58N/A getPath: function(locator) {
18N/A var path = null,
18N/A keys = [],
18N/A i = 0;
18N/A
18N/A if (locator) {
18N/A // Strip the ["string keys"] and [1] array indexes
18N/A // TODO: the first two steps can probably be reduced to one with
18N/A // /\[\s*(['"])?(.*?)\1\s*\]/g, but the array indices would be
18N/A // stored as strings. This is not likely an issue.
18N/A locator = locator.
18N/A replace(/\[\s*(['"])(.*?)\1\s*\]/g,
58N/A function (x,$1,$2) {keys[i]=$2;return '.@'+(i++);}).
18N/A replace(/\[(\d+)\]/g,
42N/A function (x,$1) {keys[i]=parseInt($1,10)|0;return '.@'+(i++);}).
18N/A replace(/^\./,''); // remove leading dot
18N/A
42N/A // Validate against problematic characters.
42N/A // commented out because the path isn't sent to eval, so it
42N/A // should be safe. I'm not sure what makes a locator invalid.
18N/A //if (!/[^\w\.\$@]/.test(locator)) {
18N/A path = locator.split('.');
18N/A for (i=path.length-1; i >= 0; --i) {
42N/A if (path[i].charAt(0) === '@') {
18N/A path[i] = keys[parseInt(path[i].substr(1),10)];
42N/A }
18N/A }
42N/A /*}
42N/A else {
42N/A Y.log("Invalid locator: " + locator, "error", "dataschema-json");
42N/A }
42N/A */
42N/A }
42N/A return path;
42N/A },
42N/A
42N/A /**
42N/A * Utility function to walk a path and return the value located there.
42N/A *
18N/A * @method getLocationValue
18N/A * @param path {String[]} Locator path.
18N/A * @param data {String} Data to traverse.
18N/A * @return {Object} Data value at location.
42N/A * @static
18N/A */
18N/A getLocationValue: function (path, data) {
42N/A var i = 0,
42N/A len = path.length;
42N/A for (;i<len;i++) {
42N/A if (isObject(data) && (path[i] in data)) {
42N/A data = data[path[i]];
42N/A } else {
42N/A data = undefined;
42N/A break;
42N/A }
42N/A }
42N/A return data;
42N/A },
42N/A
42N/A /**
42N/A Applies a schema to an array of data located in a JSON structure, returning
42N/A a normalized object with results in the `results` property. Additional
42N/A information can be parsed out of the JSON for inclusion in the `meta`
18N/A property of the response object. If an error is encountered during
18N/A processing, an `error` property will be added.
18N/A
18N/A The input _data_ is expected to be an object or array. If it is a string,
42N/A it will be passed through `Y.JSON.parse()`.
18N/A
18N/A If _data_ contains an array of data records to normalize, specify the
18N/A _schema.resultListLocator_ as a dot separated path string just as you would
18N/A reference it in JavaScript. So if your _data_ object has a record array at
18N/A _data.response.results_, use _schema.resultListLocator_ =
18N/A "response.results". Bracket notation can also be used for array indices or
18N/A object properties (e.g. "response['results']"); This is called a "path
18N/A locator"
42N/A
42N/A Field data in the result list is extracted with field identifiers in
42N/A _schema.resultFields_. Field identifiers are objects with the following
42N/A properties:
42N/A
18N/A * `key` : <strong>(required)</strong> The path locator (String)
18N/A * `parser`: A function or the name of a function on `Y.Parsers` used
42N/A to convert the input value into a normalized type. Parser
42N/A functions are passed the value as input and are expected to
18N/A return a value.
18N/A
18N/A If no value parsing is needed, you can use path locators (strings)
18N/A instead of field identifiers (objects) -- see example below.
18N/A
18N/A If no processing of the result list array is needed, _schema.resultFields_
42N/A can be omitted; the `response.results` will point directly to the array.
42N/A
42N/A If the result list contains arrays, `response.results` will contain an
18N/A array of objects with key:value pairs assuming the fields in
42N/A _schema.resultFields_ are ordered in accordance with the data array
18N/A values.
42N/A
18N/A If the result list contains objects, the identified _schema.resultFields_
42N/A will be used to extract a value from those objects for the output result.
18N/A
18N/A To extract additional information from the JSON, include an array of
18N/A path locators in _schema.metaFields_. The collected values will be
42N/A stored in `response.meta`.
18N/A
18N/A
42N/A @example
42N/A // Process array of arrays
18N/A var schema = {
42N/A resultListLocator: 'produce.fruit',
42N/A resultFields: [ 'name', 'color' ]
18N/A },
42N/A data = {
42N/A produce: {
58N/A fruit: [
42N/A [ 'Banana', 'yellow' ],
42N/A [ 'Orange', 'orange' ],
42N/A [ 'Eggplant', 'purple' ]
58N/A ]
42N/A }
42N/A };
58N/A
42N/A var response = Y.DataSchema.JSON.apply(schema, data);
42N/A
42N/A // response.results[0] is { name: "Banana", color: "yellow" }
42N/A
58N/A
42N/A // Process array of objects + some metadata
42N/A schema.metaFields = [ 'lastInventory' ];
18N/A
18N/A data = {
18N/A produce: {
58N/A fruit: [
58N/A { name: 'Banana', color: 'yellow', price: '1.96' },
58N/A { name: 'Orange', color: 'orange', price: '2.04' },
58N/A { name: 'Eggplant', color: 'purple', price: '4.31' }
58N/A ]
58N/A },
58N/A lastInventory: '2011-07-19'
42N/A };
18N/A
18N/A response = Y.DataSchema.JSON.apply(schema, data);
58N/A
58N/A // response.results[0] is { name: "Banana", color: "yellow" }
58N/A // response.meta.lastInventory is '2001-07-19'
18N/A
18N/A
42N/A // Use parsers
18N/A schema.resultFields = [
18N/A {
18N/A key: 'name',
18N/A parser: function (val) { return val.toUpperCase(); }
18N/A },
18N/A {
18N/A key: 'price',
parser: 'number' // Uses Y.Parsers.number
}
];
response = Y.DataSchema.JSON.apply(schema, data);
// Note price was converted from a numeric string to a number
// response.results[0] looks like { fruit: "BANANA", price: 1.96 }
@method apply
@param {Object} [schema] Schema to apply. Supported configuration
properties are:
@param {String} [schema.resultListLocator] Path locator for the
location of the array of records to flatten into `response.results`
@param {Array} [schema.resultFields] Field identifiers to
locate/assign values in the response records. See above for
details.
@param {Array} [schema.metaFields] Path locators to extract extra
non-record related information from the data object.
@param {Object|Array|String} data JSON data or its string serialization.
@return {Object} An Object with properties `results` and `meta`
@static
**/
apply: function(schema, data) {
var data_in = data,
data_out = { results: [], meta: {} };
// Convert incoming JSON strings
if (!isObject(data)) {
try {
data_in = Y.JSON.parse(data);
}
catch(e) {
data_out.error = e;
return data_out;
}
}
if (isObject(data_in) && schema) {
// Parse results data
data_out = SchemaJSON._parseResults.call(this, schema, data_in, data_out);
// Parse meta data
if (schema.metaFields !== undefined) {
data_out = SchemaJSON._parseMeta(schema.metaFields, data_in, data_out);
}
}
else {
Y.log("JSON data could not be schema-parsed: " + Y.dump(data) + " " + Y.dump(data), "error", "dataschema-json");
data_out.error = new Error("JSON schema parse failure");
}
return data_out;
},
/**
* Schema-parsed list of results from full data
*
* @method _parseResults
* @param schema {Object} Schema to parse against.
* @param json_in {Object} JSON to parse.
* @param data_out {Object} In-progress parsed data to update.
* @return {Object} Parsed data object.
* @static
* @protected
*/
_parseResults: function(schema, json_in, data_out) {
var getPath = SchemaJSON.getPath,
getValue = SchemaJSON.getLocationValue,
path = getPath(schema.resultListLocator),
results = path ?
(getValue(path, json_in) ||
// Fall back to treat resultListLocator as a simple key
json_in[schema.resultListLocator]) :
// Or if no resultListLocator is supplied, use the input
json_in;
if (isArray(results)) {
// if no result fields are passed in, then just take
// the results array whole-hog Sometimes you're getting
// an array of strings, or want the whole object, so
// resultFields don't make sense.
if (isArray(schema.resultFields)) {
data_out = SchemaJSON._getFieldValues.call(this, schema.resultFields, results, data_out);
} else {
data_out.results = results;
}
} else if (schema.resultListLocator) {
data_out.results = [];
data_out.error = new Error("JSON results retrieval failure");
Y.log("JSON data could not be parsed: " + Y.dump(json_in), "error", "dataschema-json");
}
return data_out;
},
/**
* Get field data values out of list of full results
*
* @method _getFieldValues
* @param fields {Array} Fields to find.
* @param array_in {Array} Results to parse.
* @param data_out {Object} In-progress parsed data to update.
* @return {Object} Parsed data object.
* @static
* @protected
*/
_getFieldValues: function(fields, array_in, data_out) {
var results = [],
len = fields.length,
i, j,
field, key, locator, path, parser, val,
simplePaths = [], complexPaths = [], fieldParsers = [],
result, record;
// First collect hashes of simple paths, complex paths, and parsers
for (i=0; i<len; i++) {
field = fields[i]; // A field can be a simple string or a hash
key = field.key || field; // Find the key
locator = field.locator || key; // Find the locator
// Validate and store locators for later
path = SchemaJSON.getPath(locator);
if (path) {
if (path.length === 1) {
simplePaths.push({
key : key,
path: path[0]
});
} else {
complexPaths.push({
key : key,
path : path,
locator: locator
});
}
} else {
Y.log("Invalid key syntax: " + key, "warn", "dataschema-json");
}
// Validate and store parsers for later
//TODO: use Y.DataSchema.parse?
parser = (isFunction(field.parser)) ?
field.parser :
Y.Parsers[field.parser + ''];
if (parser) {
fieldParsers.push({
key : key,
parser: parser
});
}
}
// Traverse list of array_in, creating records of simple fields,
// complex fields, and applying parsers as necessary
for (i=array_in.length-1; i>=0; --i) {
record = {};
result = array_in[i];
if(result) {
// Cycle through complexLocators
for (j=complexPaths.length - 1; j>=0; --j) {
path = complexPaths[j];
val = SchemaJSON.getLocationValue(path.path, result);
if (val === undefined) {
val = SchemaJSON.getLocationValue([path.locator], result);
// Fail over keys like "foo.bar" from nested parsing
// to single token parsing if a value is found in
// results["foo.bar"]
if (val !== undefined) {
simplePaths.push({
key: path.key,
path: path.locator
});
// Don't try to process the path as complex
// for further results
complexPaths.splice(i,1);
continue;
}
}
record[path.key] = Base.parse.call(this,
(SchemaJSON.getLocationValue(path.path, result)), path);
}
// Cycle through simpleLocators
for (j = simplePaths.length - 1; j >= 0; --j) {
path = simplePaths[j];
// Bug 1777850: The result might be an array instead of object
record[path.key] = Base.parse.call(this,
((result[path.path] === undefined) ?
result[j] : result[path.path]), path);
}
// Cycle through fieldParsers
for (j=fieldParsers.length-1; j>=0; --j) {
key = fieldParsers[j].key;
record[key] = fieldParsers[j].parser.call(this, record[key]);
// Safety net
if (record[key] === undefined) {
record[key] = null;
}
}
results[i] = record;
}
}
data_out.results = results;
return data_out;
},
/**
* Parses results data according to schema
*
* @method _parseMeta
* @param metaFields {Object} Metafields definitions.
* @param json_in {Object} JSON to parse.
* @param data_out {Object} In-progress parsed data to update.
* @return {Object} Schema-parsed meta data.
* @static
* @protected
*/
_parseMeta: function(metaFields, json_in, data_out) {
if (isObject(metaFields)) {
var key, path;
for(key in metaFields) {
if (metaFields.hasOwnProperty(key)) {
path = SchemaJSON.getPath(metaFields[key]);
if (path && json_in) {
data_out.meta[key] = SchemaJSON.getLocationValue(path, json_in);
}
}
}
}
else {
data_out.error = new Error("JSON meta data retrieval failure");
}
return data_out;
}
};
// TODO: Y.Object + mix() might be better here
Y.DataSchema.JSON = Y.mix(SchemaJSON, Base);
}, '@VERSION@' ,{requires:['dataschema-base','json']});