1
0
mirror of https://github.com/fluencelabs/jsonpath synced 2025-04-02 06:51:05 +00:00

86 lines
1.7 KiB
JavaScript
Raw Normal View History

2019-04-09 16:13:09 +09:00
const { CompileFn, SelectorFn, selectStr, Selector: _Selector } = require('../native');
2019-03-14 22:30:42 +09:00
function compile(path) {
2019-04-09 16:13:09 +09:00
let compile = new CompileFn(path);
2019-03-14 22:30:42 +09:00
return (json) => {
if(typeof json != 'string') {
json = JSON.stringify(json)
}
return JSON.parse(compile.template(json));
2019-03-14 22:30:42 +09:00
};
}
function selector(json) {
if(typeof json != 'string') {
json = JSON.stringify(json)
}
2019-04-09 16:13:09 +09:00
let selector = new SelectorFn(json);
2019-03-14 22:30:42 +09:00
return (path) => {
2019-04-09 16:13:09 +09:00
return JSON.parse(selector.select(path));
2019-03-14 22:30:42 +09:00
}
}
function select(json, path) {
if(typeof json != 'string') {
json = JSON.stringify(json)
}
return JSON.parse(selectStr(json, path));
2019-03-14 22:30:42 +09:00
}
2019-04-09 16:13:09 +09:00
class Selector {
constructor() {
this._selector = new _Selector();
return this;
}
path(path) {
this._selector.path(path);
return this;
}
value(json) {
if(typeof json != 'string') {
json = JSON.stringify(json)
}
2019-05-16 14:14:09 +09:00
this._selector.valueFromStr(json);
2019-04-09 16:13:09 +09:00
return this;
}
selectToStr() {
2019-05-16 14:14:09 +09:00
return this.selectAsStr();
2019-04-09 16:13:09 +09:00
}
selectTo() {
2019-05-16 14:14:09 +09:00
return this.selectAs();
2019-04-09 16:13:09 +09:00
}
2019-05-16 14:14:09 +09:00
selectAsStr() {
return this._selector.selectAsStr();
}
selectAs() {
return JSON.parse(this.selectAsStr());
}
map(func) {
this._selector.map((json) => {
var result = func.call(null, JSON.parse(json));
if(typeof result !== 'string') {
result = JSON.stringify(result);
}
return result;
});
return this;
}
get() {
return JSON.parse(this._selector.get());
}
2019-04-09 16:13:09 +09:00
}
2019-03-14 22:30:42 +09:00
module.exports = {
compile,
selector,
2019-04-09 16:13:09 +09:00
select,
Selector
2019-03-14 22:30:42 +09:00
};