-
Notifications
You must be signed in to change notification settings - Fork 232
/
Copy pathindex.js
executable file
·53 lines (44 loc) · 1.53 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env node
const path = require('path');
const fs = require('fs');
const jsonata = require('../src/jsonata');
/**
* cli usage:
* jsonata <json-file> <expression>
* cat my-file.json | jsonata <expression>
* @returns {{expression: string, object: {}}}
*/
function parseArgs() {
const args = process.argv.slice(2);
if (args.length === 2) { // file and expression given
const [jsonFile, expression] = args;
let object;
try {
object = require(path.resolve(jsonFile));
} catch (error) {
// eslint-disable-next-line no-console
console.error(`failed to load json file ${jsonFile}`, error);
process.exit(1);
}
return { object, expression };
} else if (args.length === 1) { // expression given, read file contents from stdin
const fileData = fs.readFileSync(0).toString();
let object;
try {
object = JSON.parse(fileData);
} catch (error) {
// eslint-disable-next-line no-console
console.error(`failed to load json string from stdin`, error);
process.exit(2);
}
return { object, expression: args[0] };
} else {
// eslint-disable-next-line no-console
console.error('invalid number of arguments', process.argv);
process.exit(3);
}
}
const { expression, object } = parseArgs();
const result = jsonata(expression).evaluate(object);
// eslint-disable-next-line no-console
console.log(JSON.stringify(result, null, 2));