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