Dashboard sipadu mbip
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dataschema-json-debug.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. /*
  2. Copyright (c) 2010, Yahoo! Inc. All rights reserved.
  3. Code licensed under the BSD License:
  4. http://developer.yahoo.com/yui/license.html
  5. version: 3.4.0
  6. build: nightly
  7. */
  8. YUI.add('dataschema-json', function(Y) {
  9. /**
  10. Provides a DataSchema implementation which can be used to work with JSON data.
  11. @module dataschema
  12. @submodule dataschema-json
  13. **/
  14. /**
  15. Provides a DataSchema implementation which can be used to work with JSON data.
  16. See the `apply` method for usage.
  17. @class DataSchema.JSON
  18. @extends DataSchema.Base
  19. @static
  20. **/
  21. var LANG = Y.Lang,
  22. isFunction = LANG.isFunction,
  23. isObject = LANG.isObject,
  24. isArray = LANG.isArray,
  25. // TODO: I don't think the calls to Base.* need to be done via Base since
  26. // Base is mixed into SchemaJSON. Investigate for later.
  27. Base = Y.DataSchema.Base,
  28. SchemaJSON;
  29. SchemaJSON = {
  30. /////////////////////////////////////////////////////////////////////////////
  31. //
  32. // DataSchema.JSON static methods
  33. //
  34. /////////////////////////////////////////////////////////////////////////////
  35. /**
  36. * Utility function converts JSON locator strings into walkable paths
  37. *
  38. * @method getPath
  39. * @param locator {String} JSON value locator.
  40. * @return {String[]} Walkable path to data value.
  41. * @static
  42. */
  43. getPath: function(locator) {
  44. var path = null,
  45. keys = [],
  46. i = 0;
  47. if (locator) {
  48. // Strip the ["string keys"] and [1] array indexes
  49. // TODO: the first two steps can probably be reduced to one with
  50. // /\[\s*(['"])?(.*?)\1\s*\]/g, but the array indices would be
  51. // stored as strings. This is not likely an issue.
  52. locator = locator.
  53. replace(/\[\s*(['"])(.*?)\1\s*\]/g,
  54. function (x,$1,$2) {keys[i]=$2;return '.@'+(i++);}).
  55. replace(/\[(\d+)\]/g,
  56. function (x,$1) {keys[i]=parseInt($1,10)|0;return '.@'+(i++);}).
  57. replace(/^\./,''); // remove leading dot
  58. // Validate against problematic characters.
  59. // commented out because the path isn't sent to eval, so it
  60. // should be safe. I'm not sure what makes a locator invalid.
  61. //if (!/[^\w\.\$@]/.test(locator)) {
  62. path = locator.split('.');
  63. for (i=path.length-1; i >= 0; --i) {
  64. if (path[i].charAt(0) === '@') {
  65. path[i] = keys[parseInt(path[i].substr(1),10)];
  66. }
  67. }
  68. /*}
  69. else {
  70. Y.log("Invalid locator: " + locator, "error", "dataschema-json");
  71. }
  72. */
  73. }
  74. return path;
  75. },
  76. /**
  77. * Utility function to walk a path and return the value located there.
  78. *
  79. * @method getLocationValue
  80. * @param path {String[]} Locator path.
  81. * @param data {String} Data to traverse.
  82. * @return {Object} Data value at location.
  83. * @static
  84. */
  85. getLocationValue: function (path, data) {
  86. var i = 0,
  87. len = path.length;
  88. for (;i<len;i++) {
  89. if (isObject(data) && (path[i] in data)) {
  90. data = data[path[i]];
  91. } else {
  92. data = undefined;
  93. break;
  94. }
  95. }
  96. return data;
  97. },
  98. /**
  99. Applies a schema to an array of data located in a JSON structure, returning
  100. a normalized object with results in the `results` property. Additional
  101. information can be parsed out of the JSON for inclusion in the `meta`
  102. property of the response object. If an error is encountered during
  103. processing, an `error` property will be added.
  104. The input _data_ is expected to be an object or array. If it is a string,
  105. it will be passed through `Y.JSON.parse()`.
  106. If _data_ contains an array of data records to normalize, specify the
  107. _schema.resultListLocator_ as a dot separated path string just as you would
  108. reference it in JavaScript. So if your _data_ object has a record array at
  109. _data.response.results_, use _schema.resultListLocator_ =
  110. "response.results". Bracket notation can also be used for array indices or
  111. object properties (e.g. "response['results']"); This is called a "path
  112. locator"
  113. Field data in the result list is extracted with field identifiers in
  114. _schema.resultFields_. Field identifiers are objects with the following
  115. properties:
  116. * `key` : <strong>(required)</strong> The path locator (String)
  117. * `parser`: A function or the name of a function on `Y.Parsers` used
  118. to convert the input value into a normalized type. Parser
  119. functions are passed the value as input and are expected to
  120. return a value.
  121. If no value parsing is needed, you can use path locators (strings)
  122. instead of field identifiers (objects) -- see example below.
  123. If no processing of the result list array is needed, _schema.resultFields_
  124. can be omitted; the `response.results` will point directly to the array.
  125. If the result list contains arrays, `response.results` will contain an
  126. array of objects with key:value pairs assuming the fields in
  127. _schema.resultFields_ are ordered in accordance with the data array
  128. values.
  129. If the result list contains objects, the identified _schema.resultFields_
  130. will be used to extract a value from those objects for the output result.
  131. To extract additional information from the JSON, include an array of
  132. path locators in _schema.metaFields_. The collected values will be
  133. stored in `response.meta`.
  134. @example
  135. // Process array of arrays
  136. var schema = {
  137. resultListLocator: 'produce.fruit',
  138. resultFields: [ 'name', 'color' ]
  139. },
  140. data = {
  141. produce: {
  142. fruit: [
  143. [ 'Banana', 'yellow' ],
  144. [ 'Orange', 'orange' ],
  145. [ 'Eggplant', 'purple' ]
  146. ]
  147. }
  148. };
  149. var response = Y.DataSchema.JSON.apply(schema, data);
  150. // response.results[0] is { name: "Banana", color: "yellow" }
  151. // Process array of objects + some metadata
  152. schema.metaFields = [ 'lastInventory' ];
  153. data = {
  154. produce: {
  155. fruit: [
  156. { name: 'Banana', color: 'yellow', price: '1.96' },
  157. { name: 'Orange', color: 'orange', price: '2.04' },
  158. { name: 'Eggplant', color: 'purple', price: '4.31' }
  159. ]
  160. },
  161. lastInventory: '2011-07-19'
  162. };
  163. response = Y.DataSchema.JSON.apply(schema, data);
  164. // response.results[0] is { name: "Banana", color: "yellow" }
  165. // response.meta.lastInventory is '2001-07-19'
  166. // Use parsers
  167. schema.resultFields = [
  168. {
  169. key: 'name',
  170. parser: function (val) { return val.toUpperCase(); }
  171. },
  172. {
  173. key: 'price',
  174. parser: 'number' // Uses Y.Parsers.number
  175. }
  176. ];
  177. response = Y.DataSchema.JSON.apply(schema, data);
  178. // Note price was converted from a numeric string to a number
  179. // response.results[0] looks like { fruit: "BANANA", price: 1.96 }
  180. @method apply
  181. @param {Object} [schema] Schema to apply. Supported configuration
  182. properties are:
  183. @param {String} [schema.resultListLocator] Path locator for the
  184. location of the array of records to flatten into `response.results`
  185. @param {Array} [schema.resultFields] Field identifiers to
  186. locate/assign values in the response records. See above for
  187. details.
  188. @param {Array} [schema.metaFields] Path locators to extract extra
  189. non-record related information from the data object.
  190. @param {Object|Array|String} data JSON data or its string serialization.
  191. @return {Object} An Object with properties `results` and `meta`
  192. @static
  193. **/
  194. apply: function(schema, data) {
  195. var data_in = data,
  196. data_out = { results: [], meta: {} };
  197. // Convert incoming JSON strings
  198. if (!isObject(data)) {
  199. try {
  200. data_in = Y.JSON.parse(data);
  201. }
  202. catch(e) {
  203. data_out.error = e;
  204. return data_out;
  205. }
  206. }
  207. if (isObject(data_in) && schema) {
  208. // Parse results data
  209. data_out = SchemaJSON._parseResults.call(this, schema, data_in, data_out);
  210. // Parse meta data
  211. if (schema.metaFields !== undefined) {
  212. data_out = SchemaJSON._parseMeta(schema.metaFields, data_in, data_out);
  213. }
  214. }
  215. else {
  216. Y.log("JSON data could not be schema-parsed: " + Y.dump(data) + " " + Y.dump(data), "error", "dataschema-json");
  217. data_out.error = new Error("JSON schema parse failure");
  218. }
  219. return data_out;
  220. },
  221. /**
  222. * Schema-parsed list of results from full data
  223. *
  224. * @method _parseResults
  225. * @param schema {Object} Schema to parse against.
  226. * @param json_in {Object} JSON to parse.
  227. * @param data_out {Object} In-progress parsed data to update.
  228. * @return {Object} Parsed data object.
  229. * @static
  230. * @protected
  231. */
  232. _parseResults: function(schema, json_in, data_out) {
  233. var getPath = SchemaJSON.getPath,
  234. getValue = SchemaJSON.getLocationValue,
  235. path = getPath(schema.resultListLocator),
  236. results = path ?
  237. (getValue(path, json_in) ||
  238. // Fall back to treat resultListLocator as a simple key
  239. json_in[schema.resultListLocator]) :
  240. // Or if no resultListLocator is supplied, use the input
  241. json_in;
  242. if (isArray(results)) {
  243. // if no result fields are passed in, then just take
  244. // the results array whole-hog Sometimes you're getting
  245. // an array of strings, or want the whole object, so
  246. // resultFields don't make sense.
  247. if (isArray(schema.resultFields)) {
  248. data_out = SchemaJSON._getFieldValues.call(this, schema.resultFields, results, data_out);
  249. } else {
  250. data_out.results = results;
  251. }
  252. } else if (schema.resultListLocator) {
  253. data_out.results = [];
  254. data_out.error = new Error("JSON results retrieval failure");
  255. Y.log("JSON data could not be parsed: " + Y.dump(json_in), "error", "dataschema-json");
  256. }
  257. return data_out;
  258. },
  259. /**
  260. * Get field data values out of list of full results
  261. *
  262. * @method _getFieldValues
  263. * @param fields {Array} Fields to find.
  264. * @param array_in {Array} Results to parse.
  265. * @param data_out {Object} In-progress parsed data to update.
  266. * @return {Object} Parsed data object.
  267. * @static
  268. * @protected
  269. */
  270. _getFieldValues: function(fields, array_in, data_out) {
  271. var results = [],
  272. len = fields.length,
  273. i, j,
  274. field, key, locator, path, parser, val,
  275. simplePaths = [], complexPaths = [], fieldParsers = [],
  276. result, record;
  277. // First collect hashes of simple paths, complex paths, and parsers
  278. for (i=0; i<len; i++) {
  279. field = fields[i]; // A field can be a simple string or a hash
  280. key = field.key || field; // Find the key
  281. locator = field.locator || key; // Find the locator
  282. // Validate and store locators for later
  283. path = SchemaJSON.getPath(locator);
  284. if (path) {
  285. if (path.length === 1) {
  286. simplePaths.push({
  287. key : key,
  288. path: path[0]
  289. });
  290. } else {
  291. complexPaths.push({
  292. key : key,
  293. path : path,
  294. locator: locator
  295. });
  296. }
  297. } else {
  298. Y.log("Invalid key syntax: " + key, "warn", "dataschema-json");
  299. }
  300. // Validate and store parsers for later
  301. //TODO: use Y.DataSchema.parse?
  302. parser = (isFunction(field.parser)) ?
  303. field.parser :
  304. Y.Parsers[field.parser + ''];
  305. if (parser) {
  306. fieldParsers.push({
  307. key : key,
  308. parser: parser
  309. });
  310. }
  311. }
  312. // Traverse list of array_in, creating records of simple fields,
  313. // complex fields, and applying parsers as necessary
  314. for (i=array_in.length-1; i>=0; --i) {
  315. record = {};
  316. result = array_in[i];
  317. if(result) {
  318. // Cycle through complexLocators
  319. for (j=complexPaths.length - 1; j>=0; --j) {
  320. path = complexPaths[j];
  321. val = SchemaJSON.getLocationValue(path.path, result);
  322. if (val === undefined) {
  323. val = SchemaJSON.getLocationValue([path.locator], result);
  324. // Fail over keys like "foo.bar" from nested parsing
  325. // to single token parsing if a value is found in
  326. // results["foo.bar"]
  327. if (val !== undefined) {
  328. simplePaths.push({
  329. key: path.key,
  330. path: path.locator
  331. });
  332. // Don't try to process the path as complex
  333. // for further results
  334. complexPaths.splice(i,1);
  335. continue;
  336. }
  337. }
  338. record[path.key] = Base.parse.call(this,
  339. (SchemaJSON.getLocationValue(path.path, result)), path);
  340. }
  341. // Cycle through simpleLocators
  342. for (j = simplePaths.length - 1; j >= 0; --j) {
  343. path = simplePaths[j];
  344. // Bug 1777850: The result might be an array instead of object
  345. record[path.key] = Base.parse.call(this,
  346. ((result[path.path] === undefined) ?
  347. result[j] : result[path.path]), path);
  348. }
  349. // Cycle through fieldParsers
  350. for (j=fieldParsers.length-1; j>=0; --j) {
  351. key = fieldParsers[j].key;
  352. record[key] = fieldParsers[j].parser.call(this, record[key]);
  353. // Safety net
  354. if (record[key] === undefined) {
  355. record[key] = null;
  356. }
  357. }
  358. results[i] = record;
  359. }
  360. }
  361. data_out.results = results;
  362. return data_out;
  363. },
  364. /**
  365. * Parses results data according to schema
  366. *
  367. * @method _parseMeta
  368. * @param metaFields {Object} Metafields definitions.
  369. * @param json_in {Object} JSON to parse.
  370. * @param data_out {Object} In-progress parsed data to update.
  371. * @return {Object} Schema-parsed meta data.
  372. * @static
  373. * @protected
  374. */
  375. _parseMeta: function(metaFields, json_in, data_out) {
  376. if (isObject(metaFields)) {
  377. var key, path;
  378. for(key in metaFields) {
  379. if (metaFields.hasOwnProperty(key)) {
  380. path = SchemaJSON.getPath(metaFields[key]);
  381. if (path && json_in) {
  382. data_out.meta[key] = SchemaJSON.getLocationValue(path, json_in);
  383. }
  384. }
  385. }
  386. }
  387. else {
  388. data_out.error = new Error("JSON meta data retrieval failure");
  389. }
  390. return data_out;
  391. }
  392. };
  393. // TODO: Y.Object + mix() might be better here
  394. Y.DataSchema.JSON = Y.mix(SchemaJSON, Base);
  395. }, '3.4.0' ,{requires:['dataschema-base','json']});