UNPKG

@jsonhero/parser

Version:

A parser that walks through a JSON file and for each value determines the path to it, the type and paths to any children. It also builds a model of the structure of the data.

84 lines (80 loc) 2.37 kB
import { JSONHeroPath } from '@jsonhero/path'; import { inferType } from '@jsonhero/json-infer-types'; function friendlyName(name) { name = snakeCase(name); name = dashCase(name); name = camelCase(name); name = toTitleCase(name); return name; } function camelCase(name) { return (name // insert a space before all caps .replace(/(\w)([A-Z])/g, '$1 $2')); } function snakeCase(name) { return (name // insert a space before all caps .replace(/(_)/g, ' ')); } function dashCase(name) { return (name // insert a space before all caps .replace(/(-)/g, ' ')); } function toTitleCase(name) { return (name //after every space .replace(/ ([a-z])/g, function (str) { return str.toUpperCase(); }) //first character .replace(/^./, function (str) { return str.toUpperCase(); })); } function parse(object) { var rootPath = '$'; var parsedObject = { values: { rootPath: rootPath, values: {}, }, structure: { rootPath: rootPath, values: {}, }, }; buildValueTree(object, rootPath, 'Root', parsedObject.values.values); return parsedObject; } function buildValueTree(object, path, name, valueCollection) { var valueInfo = { path: path, name: name, displayName: friendlyName(name), value: object, type: inferType(object), children: null, }; valueCollection[path] = valueInfo; //for any children add to children and then recursively run this if (isCollection(valueInfo.type)) { var parentPath = new JSONHeroPath(path); valueInfo.children = []; for (var key in object) { var child = object[key]; var childPath = parentPath.child(key).toString(); valueInfo.children.push(childPath); var childName = key; if (valueInfo.type.name === 'array') { childName = "".concat(name, " ").concat(key); } buildValueTree(child, childPath, childName, valueCollection); } } } function isCollection(type) { return type.name === 'array' || type.name === 'object'; } export { parse };