Skip to content

Commit

Permalink
Merge 5bf2d59 into af4cd53
Browse files Browse the repository at this point in the history
  • Loading branch information
srl295 committed Jul 10, 2018
2 parents af4cd53 + 5bf2d59 commit c28ec38
Show file tree
Hide file tree
Showing 18 changed files with 1,580 additions and 1,253 deletions.
47 changes: 28 additions & 19 deletions lib/flatten.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

const jsonpath = require('jsonpath');
const jsonpath = require('@evxn/jsonpath');

/**
* Flatten a deeply nested object into its jsonpath equivalent
Expand All @@ -29,7 +29,10 @@ module.exports.flatten = function flatten(obj, opts) {
return jsonpath
.nodes(obj, '$..*')
.reduce((p,v) => {
if ( !opts.flattenAll && typeof v.value === 'string' && v.path.length === 2) {
if ( !opts.flattenAll &&
typeof v.value === 'string' &&
v.path.length === 2 &&
v.path[1].substring(0,2) !== '$.') {
// It is a simple {key: "value"} … do not modify it
p[v.path[1]] = v.value;
} else if ( typeof v.value !== 'object') {
Expand Down Expand Up @@ -66,6 +69,11 @@ module.exports._apply =
function _apply(root, k, v) {
// parse the path
let path;
if(k[0] !== '$') {
// no JSONpath prefix—ignore
root[k] = v;
return root;
}
try {
path = jsonpath.parse(k);
} catch (e) {
Expand All @@ -74,18 +82,11 @@ function _apply(root, k, v) {
root[k]=v;
return root;
}
path[path.length-1].last = true; // mark last
/*istanbul ignore next*/ _DEBUG && console.dir(path);
path.reduce((cur, pe) => {
/*istanbul ignore next*/ if(_DEBUG) {
console.log('root=');
console.dir(root);
console.log('cur=');
console.dir(cur);
}
let cur = root;
for(let n=0; n<path.length; n++) {
const pe = path[n];
if(pe.expression.type === 'root' && pe.expression.value === '$') {
/*istanbul ignore next*/ _DEBUG && console.log('$');
return root; // root
cur = root; // root
} else if(
// ….baz
(pe.expression.type === 'string_literal'
Expand All @@ -101,17 +102,25 @@ function _apply(root, k, v) {
|| (pe.expression.type === 'numeric_literal'
&& pe.scope === 'child'
&& pe.operation === 'subscript')) {
if(!pe.last) {
/*istanbul ignore next*/ _DEBUG && console.log('Traversing',pe.expression.value);
return (cur[pe.expression.value] = (cur[pe.expression.value] || {}));
} else {
const pxv = pe.expression.value;
if(path[n+1]) { // not last
cur = cur[pxv] = ( cur[pxv] || emptyFor(path[n+1].expression.type));
} else { // last
/*istanbul ignore next*/ _DEBUG && console.log('Setting',pe.expression.value,v);
cur[pe.expression.value] = v; // set string value
return cur;
//cur = cur;
}
} else {
/*istanbul ignore next*/ throw Error('Could not apply expression: ' + JSON.stringify(pe) + ' in ' + k);
}
},root);
}
return root;
};

function emptyFor(t) {
if(t === 'numeric_literal') {
return [];
} else {
return {};
}
}
Loading

0 comments on commit c28ec38

Please sign in to comment.