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

Filter support js function #34

Open
qifuren1985 opened this issue Dec 2, 2016 · 5 comments
Open

Filter support js function #34

qifuren1985 opened this issue Dec 2, 2016 · 5 comments

Comments

@qifuren1985
Copy link

some json need complex step to filter, so If JSON-Splora support write js function in filter, we can do more things other than filter, for example, generate new data.

@wellsjo
Copy link
Owner

wellsjo commented Dec 2, 2016

Do you have a proposed spec for this? I'm open to suggestions.

@qifuren1985
Copy link
Author

qifuren1985 commented Dec 2, 2016

for exeample, modify Editor.js(line 156) to this:

    let script = filter.startsWith('.') ? '$$' + filter : filter
    let context = {
      '$$': this.data
    }

    try {
      let ret = new vm.Script(script).runInNewContext(context)
      if (ret != undefined) {
        this.emit('filter-valid', {
          result: ret,
          type: 'js'
        })
      } else {
        this.emit('filter-invalid')
      }
    } catch (e) {

      // If JavaScript filter fails, run through jq
      jq.run(filter, this.data, {
        input: 'json',
        output: 'json'
      }).then(result => {
        if (result === null) {

          // jq returns null for incorrect keys, but we will count them as
          // invalid
          this.emit('filter-invalid')
        } else {

          // The jq filter worked
          this.emit('filter-valid', {
            result: result,
            type: 'jq'
          })
        }
      }).catch(e => {

        // jq filter failed
        this.emit('filter-invalid')
      });
    }

After modify the code, we can type js function($$ is input json):
.length
a={"b":1}
(function(){return [1,2,3]})()
(function(s){return s[0]})($$)

@wellsjo
Copy link
Owner

wellsjo commented Dec 2, 2016

Ah yes, giving access to a the data object through a variable such as $$ would work. I will explore this later.

@qifuren1985
Copy link
Author

qifuren1985 commented Dec 2, 2016

In Editor.js, line 166 has a bug. if result is empty string or 0, it will be false.
if (context.result) { ..... }
should be
if (context.result != undefined) { ..... }

test code:
if(""){alert(1)}
if(0){alert(1)}

@wellsjo
Copy link
Owner

wellsjo commented Dec 2, 2016

@qifuren1985 can you report that as a separate issue and label it as a bug?

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

2 participants