jsonpath-object-transform icon indicating copy to clipboard operation
jsonpath-object-transform copied to clipboard

Request: Transform items using custom callback

Open t-moe opened this issue 8 years ago • 3 comments

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).

t-moe avatar Apr 06 '16 08:04 t-moe

I like the idea

dvdln avatar May 03 '16 21:05 dvdln

ya, I also would love this feature

abhishek-nair avatar May 13 '16 16:05 abhishek-nair

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?

wolfc86 avatar Sep 07 '16 15:09 wolfc86