@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.
88 lines (82 loc) • 2.48 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var path = require('@jsonhero/path');
var jsonInferTypes = require('@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$1, name, valueCollection) {
var valueInfo = {
path: path$1,
name: name,
displayName: friendlyName(name),
value: object,
type: jsonInferTypes.inferType(object),
children: null,
};
valueCollection[path$1] = valueInfo;
//for any children add to children and then recursively run this
if (isCollection(valueInfo.type)) {
var parentPath = new path.JSONHeroPath(path$1);
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';
}
exports.parse = parse;