jsonpath-object-transform
jsonpath-object-transform copied to clipboard
Request: Transform items using custom callback
It would be nice to be able to transform items of an array using a custom callback.
Possible Syntax: (Chapter: Transform Items Returned in Array)
{ destination: ['$.path.to.sources', function(item) { return someTransformations(item); } ] }
Maybe that could also be added to transform single properties? (You would have to find a good syntax for that though).
I like the idea
ya, I also would love this feature
I had a need for this as well. We made the following changes to the end of the switch statement (in the original code, this switch statement is in lines 37-49):
switch (type(path)) {
case 'string':
fn = seekSingle;
break;
case 'array':
fn = seekArray;
break;
case 'object':
fn = seekObject;
break;
case 'function':
fn = path;
break;
}
This essentially allows you to define a custom parsing function in your template (it matches the API that jsonpath-object-transform uses internally on its seek* methods).
Example usage would be:
var unparsed = {
name: {
first: 'Susie',
last: 'Q'
}
}
var template = {
name: {
first: '$.name.first',
last: '$.name.last',
display: function(data, path, result, key) {
var query = JSONPath({json: data, path: '$.name'})[0];
result[key] = query.first + ' ' + query.last;
},
},
}
var parsed = transform(unparsed, template);
parsed.name.display
would then result in 'Susie Q'.
Of course you could set the property after the transform has taken place... but having it be mixed in with the rest of your simple transformations keeps it declarative.
@t-moe for your use case, you could just use JSONPath directly to get the array you're interested in; perform your special handling, and then set result[key]
to your result.
Thoughts?