Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Request: Transform items using custom callback #7

Open
t-moe opened this issue Apr 6, 2016 · 3 comments
Open

Request: Transform items using custom callback #7

t-moe opened this issue Apr 6, 2016 · 3 comments

Comments

@t-moe
Copy link

t-moe commented Apr 6, 2016

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

@dvdln
Copy link
Owner

dvdln commented May 3, 2016

I like the idea

@abhishek-nair
Copy link

ya, I also would love this feature

@wolfc86
Copy link

wolfc86 commented Sep 7, 2016

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?

lievenjanssen added a commit to lievenjanssen/jsonpath-object-transform that referenced this issue Apr 5, 2017
lievenjanssen added a commit to lievenjanssen/jsonpath-object-transform that referenced this issue Apr 5, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants