parser.js (1694B)
1 var util = require('../util'); 2 3 function JsonParser() { } 4 5 JsonParser.prototype.parse = function(value, shape) { 6 return translate(JSON.parse(value), shape); 7 }; 8 9 function translate(value, shape) { 10 if (!shape || value === undefined) return undefined; 11 12 switch (shape.type) { 13 case 'structure': return translateStructure(value, shape); 14 case 'map': return translateMap(value, shape); 15 case 'list': return translateList(value, shape); 16 default: return translateScalar(value, shape); 17 } 18 } 19 20 function translateStructure(structure, shape) { 21 if (structure == null) return undefined; 22 23 var struct = {}; 24 var shapeMembers = shape.members; 25 util.each(shapeMembers, function(name, memberShape) { 26 var locationName = memberShape.isLocationName ? memberShape.name : name; 27 if (Object.prototype.hasOwnProperty.call(structure, locationName)) { 28 var value = structure[locationName]; 29 var result = translate(value, memberShape); 30 if (result !== undefined) struct[name] = result; 31 } 32 }); 33 return struct; 34 } 35 36 function translateList(list, shape) { 37 if (list == null) return undefined; 38 39 var out = []; 40 util.arrayEach(list, function(value) { 41 var result = translate(value, shape.member); 42 if (result === undefined) out.push(null); 43 else out.push(result); 44 }); 45 return out; 46 } 47 48 function translateMap(map, shape) { 49 if (map == null) return undefined; 50 51 var out = {}; 52 util.each(map, function(key, value) { 53 var result = translate(value, shape.value); 54 if (result === undefined) out[key] = null; 55 else out[key] = result; 56 }); 57 return out; 58 } 59 60 function translateScalar(value, shape) { 61 return shape.toType(value); 62 } 63 64 module.exports = JsonParser;