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.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. }
  71. */
  72. }
  73. return path;
  74. },
  75. /**
  76. * Utility function to walk a path and return the value located there.
  77. *
  78. * @method getLocationValue
  79. * @param path {String[]} Locator path.
  80. * @param data {String} Data to traverse.
  81. * @return {Object} Data value at location.
  82. * @static
  83. */
  84. getLocationValue: function (path, data) {
  85. var i = 0,
  86. len = path.length;
  87. for (;i<len;i++) {
  88. if (isObject(data) && (path[i] in data)) {
  89. data = data[path[i]];
  90. } else {
  91. data = undefined;
  92. break;
  93. }
  94. }
  95. return data;
  96. },
  97. /**
  98. Applies a schema to an array of data located in a JSON structure, returning
  99. a normalized object with results in the `results` property. Additional
  100. information can be parsed out of the JSON for inclusion in the `meta`
  101. property of the response object. If an error is encountered during
  102. processing, an `error` property will be added.
  103. The input _data_ is expected to be an object or array. If it is a string,
  104. it will be passed through `Y.JSON.parse()`.
  105. If _data_ contains an array of data records to normalize, specify the
  106. _schema.resultListLocator_ as a dot separated path string just as you would
  107. reference it in JavaScript. So if your _data_ object has a record array at
  108. _data.response.results_, use _schema.resultListLocator_ =
  109. "response.results". Bracket notation can also be used for array indices or
  110. object properties (e.g. "response['results']"); This is called a "path
  111. locator"
  112. Field data in the result list is extracted with field identifiers in
  113. _schema.resultFields_. Field identifiers are objects with the following
  114. properties:
  115. * `key` : <strong>(required)</strong> The path locator (String)
  116. * `parser`: A function or the name of a function on `Y.Parsers` used
  117. to convert the input value into a normalized type. Parser
  118. functions are passed the value as input and are expected to
  119. return a value.
  120. If no value parsing is needed, you can use path locators (strings)
  121. instead of field identifiers (objects) -- see example below.
  122. If no processing of the result list array is needed, _schema.resultFields_
  123. can be omitted; the `response.results` will point directly to the array.
  124. If the result list contains arrays, `response.results` will contain an
  125. array of objects with key:value pairs assuming the fields in
  126. _schema.resultFields_ are ordered in accordance with the data array
  127. values.
  128. If the result list contains objects, the identified _schema.resultFields_
  129. will be used to extract a value from those objects for the output result.
  130. To extract additional information from the JSON, include an array of
  131. path locators in _schema.metaFields_. The collected values will be
  132. stored in `response.meta`.
  133. @example
  134. // Process array of arrays
  135. var schema = {
  136. resultListLocator: 'produce.fruit',
  137. resultFields: [ 'name', 'color' ]
  138. },
  139. data = {
  140. produce: {
  141. fruit: [
  142. [ 'Banana', 'yellow' ],
  143. [ 'Orange', 'orange' ],
  144. [ 'Eggplant', 'purple' ]
  145. ]
  146. }
  147. };
  148. var response = Y.DataSchema.JSON.apply(schema, data);
  149. // response.results[0] is { name: "Banana", color: "yellow" }
  150. // Process array of objects + some metadata
  151. schema.metaFields = [ 'lastInventory' ];
  152. data = {
  153. produce: {
  154. fruit: [
  155. { name: 'Banana', color: 'yellow', price: '1.96' },
  156. { name: 'Orange', color: 'orange', price: '2.04' },
  157. { name: 'Eggplant', color: 'purple', price: '4.31' }
  158. ]
  159. },
  160. lastInventory: '2011-07-19'
  161. };
  162. response = Y.DataSchema.JSON.apply(schema, data);
  163. // response.results[0] is { name: "Banana", color: "yellow" }
  164. // response.meta.lastInventory is '2001-07-19'
  165. // Use parsers
  166. schema.resultFields = [
  167. {
  168. key: 'name',
  169. parser: function (val) { return val.toUpperCase(); }
  170. },
  171. {
  172. key: 'price',
  173. parser: 'number' // Uses Y.Parsers.number
  174. }
  175. ];
  176. response = Y.DataSchema.JSON.apply(schema, data);
  177. // Note price was converted from a numeric string to a number
  178. // response.results[0] looks like { fruit: "BANANA", price: 1.96 }
  179. @method apply
  180. @param {Object} [schema] Schema to apply. Supported configuration
  181. properties are:
  182. @param {String} [schema.resultListLocator] Path locator for the
  183. location of the array of records to flatten into `response.results`
  184. @param {Array} [schema.resultFields] Field identifiers to
  185. locate/assign values in the response records. See above for
  186. details.
  187. @param {Array} [schema.metaFields] Path locators to extract extra
  188. non-record related information from the data object.
  189. @param {Object|Array|String} data JSON data or its string serialization.
  190. @return {Object} An Object with properties `results` and `meta`
  191. @static
  192. **/
  193. apply: function(schema, data) {
  194. var data_in = data,
  195. data_out = { results: [], meta: {} };
  196. // Convert incoming JSON strings
  197. if (!isObject(data)) {
  198. try {
  199. data_in = Y.JSON.parse(data);
  200. }
  201. catch(e) {
  202. data_out.error = e;
  203. return data_out;
  204. }
  205. }
  206. if (isObject(data_in) && schema) {
  207. // Parse results data
  208. data_out = SchemaJSON._parseResults.call(this, schema, data_in, data_out);
  209. // Parse meta data
  210. if (schema.metaFields !== undefined) {
  211. data_out = SchemaJSON._parseMeta(schema.metaFields, data_in, data_out);
  212. }
  213. }
  214. else {
  215. data_out.error = new Error("JSON schema parse failure");
  216. }
  217. return data_out;
  218. },
  219. /**
  220. * Schema-parsed list of results from full data
  221. *
  222. * @method _parseResults
  223. * @param schema {Object} Schema to parse against.
  224. * @param json_in {Object} JSON to parse.
  225. * @param data_out {Object} In-progress parsed data to update.
  226. * @return {Object} Parsed data object.
  227. * @static
  228. * @protected
  229. */
  230. _parseResults: function(schema, json_in, data_out) {
  231. var getPath = SchemaJSON.getPath,
  232. getValue = SchemaJSON.getLocationValue,
  233. path = getPath(schema.resultListLocator),
  234. results = path ?
  235. (getValue(path, json_in) ||
  236. // Fall back to treat resultListLocator as a simple key
  237. json_in[schema.resultListLocator]) :
  238. // Or if no resultListLocator is supplied, use the input
  239. json_in;
  240. if (isArray(results)) {
  241. // if no result fields are passed in, then just take
  242. // the results array whole-hog Sometimes you're getting
  243. // an array of strings, or want the whole object, so
  244. // resultFields don't make sense.
  245. if (isArray(schema.resultFields)) {
  246. data_out = SchemaJSON._getFieldValues.call(this, schema.resultFields, results, data_out);
  247. } else {
  248. data_out.results = results;
  249. }
  250. } else if (schema.resultListLocator) {
  251. data_out.results = [];
  252. data_out.error = new Error("JSON results retrieval failure");
  253. }
  254. return data_out;
  255. },
  256. /**
  257. * Get field data values out of list of full results
  258. *
  259. * @method _getFieldValues
  260. * @param fields {Array} Fields to find.
  261. * @param array_in {Array} Results to parse.
  262. * @param data_out {Object} In-progress parsed data to update.
  263. * @return {Object} Parsed data object.
  264. * @static
  265. * @protected
  266. */
  267. _getFieldValues: function(fields, array_in, data_out) {
  268. var results = [],
  269. len = fields.length,
  270. i, j,
  271. field, key, locator, path, parser, val,
  272. simplePaths = [], complexPaths = [], fieldParsers = [],
  273. result, record;
  274. // First collect hashes of simple paths, complex paths, and parsers
  275. for (i=0; i<len; i++) {
  276. field = fields[i]; // A field can be a simple string or a hash
  277. key = field.key || field; // Find the key
  278. locator = field.locator || key; // Find the locator
  279. // Validate and store locators for later
  280. path = SchemaJSON.getPath(locator);
  281. if (path) {
  282. if (path.length === 1) {
  283. simplePaths.push({
  284. key : key,
  285. path: path[0]
  286. });
  287. } else {
  288. complexPaths.push({
  289. key : key,
  290. path : path,
  291. locator: locator
  292. });
  293. }
  294. } else {
  295. }
  296. // Validate and store parsers for later
  297. //TODO: use Y.DataSchema.parse?
  298. parser = (isFunction(field.parser)) ?
  299. field.parser :
  300. Y.Parsers[field.parser + ''];
  301. if (parser) {
  302. fieldParsers.push({
  303. key : key,
  304. parser: parser
  305. });
  306. }
  307. }
  308. // Traverse list of array_in, creating records of simple fields,
  309. // complex fields, and applying parsers as necessary
  310. for (i=array_in.length-1; i>=0; --i) {
  311. record = {};
  312. result = array_in[i];
  313. if(result) {
  314. // Cycle through complexLocators
  315. for (j=complexPaths.length - 1; j>=0; --j) {
  316. path = complexPaths[j];
  317. val = SchemaJSON.getLocationValue(path.path, result);
  318. if (val === undefined) {
  319. val = SchemaJSON.getLocationValue([path.locator], result);
  320. // Fail over keys like "foo.bar" from nested parsing
  321. // to single token parsing if a value is found in
  322. // results["foo.bar"]
  323. if (val !== undefined) {
  324. simplePaths.push({
  325. key: path.key,
  326. path: path.locator
  327. });
  328. // Don't try to process the path as complex
  329. // for further results
  330. complexPaths.splice(i,1);
  331. continue;
  332. }
  333. }
  334. record[path.key] = Base.parse.call(this,
  335. (SchemaJSON.getLocationValue(path.path, result)), path);
  336. }
  337. // Cycle through simpleLocators
  338. for (j = simplePaths.length - 1; j >= 0; --j) {
  339. path = simplePaths[j];
  340. // Bug 1777850: The result might be an array instead of object
  341. record[path.key] = Base.parse.call(this,
  342. ((result[path.path] === undefined) ?
  343. result[j] : result[path.path]), path);
  344. }
  345. // Cycle through fieldParsers
  346. for (j=fieldParsers.length-1; j>=0; --j) {
  347. key = fieldParsers[j].key;
  348. record[key] = fieldParsers[j].parser.call(this, record[key]);
  349. // Safety net
  350. if (record[key] === undefined) {
  351. record[key] = null;
  352. }
  353. }
  354. results[i] = record;
  355. }
  356. }
  357. data_out.results = results;
  358. return data_out;
  359. },
  360. /**
  361. * Parses results data according to schema
  362. *
  363. * @method _parseMeta
  364. * @param metaFields {Object} Metafields definitions.
  365. * @param json_in {Object} JSON to parse.
  366. * @param data_out {Object} In-progress parsed data to update.
  367. * @return {Object} Schema-parsed meta data.
  368. * @static
  369. * @protected
  370. */
  371. _parseMeta: function(metaFields, json_in, data_out) {
  372. if (isObject(metaFields)) {
  373. var key, path;
  374. for(key in metaFields) {
  375. if (metaFields.hasOwnProperty(key)) {
  376. path = SchemaJSON.getPath(metaFields[key]);
  377. if (path && json_in) {
  378. data_out.meta[key] = SchemaJSON.getLocationValue(path, json_in);
  379. }
  380. }
  381. }
  382. }
  383. else {
  384. data_out.error = new Error("JSON meta data retrieval failure");
  385. }
  386. return data_out;
  387. }
  388. };
  389. // TODO: Y.Object + mix() might be better here
  390. Y.DataSchema.JSON = Y.mix(SchemaJSON, Base);
  391. }, '3.4.0' ,{requires:['dataschema-base','json']});