wellsjo / JSON-Splora

GUI app for editing, visualizing, and manipulating JSON data
MIT License
1.86k stars 60 forks source link

Filter support js function #34

Open qifuren1985 opened 7 years ago

qifuren1985 commented 7 years ago

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 commented 7 years ago

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

qifuren1985 commented 7 years ago

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 commented 7 years ago

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

qifuren1985 commented 7 years ago

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 commented 7 years ago

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