もた日記

くだらないことを真面目にやる

JSONの処理で使えそうなコマンドラインツール(json.tool, jo, jq, jid, gron, jp, json-server, json2csv, jsondiffpatch)

JSONの処理で使えそうなコマンドラインツールを簡単に試してみる。

python -m json.tool

19.2. json — JSON エンコーダおよびデコーダ — Python 3.6.5 ドキュメント

Pythonのjson.toolモジュールは JSON オブジェクトの検証と整形出力ができる。infileoutfile引数を指定しない場合は、それぞれ標準入力、標準出力が使われる。

$ python -m json.tool --help
usage: python -m json.tool [-h] [--sort-keys] [infile] [outfile]

A simple command line interface for json module to validate and pretty-print
JSON objects.

positional arguments:
  infile       a JSON file to be validated or pretty-printed
  outfile      write the output of infile to outfile

optional arguments:
  -h, --help   show this help message and exit
  --sort-keys  sort the output of dictionaries alphabetically by key
$ echo '{"json":"obj"}' | python -m json.tool
{
    "json": "obj"
}
$ echo '{"b":1, "a":0}' | python -m json.tool --sort-keys
{
    "a": 0,
    "b": 1
}
$ echo '{1.2:3.4}' | python -m json.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

jo

github.com

joはJSONオブジェクトを生成するツール。
インストールはReleases · jpmens/jo · GitHubからファイルをダウンロードして下記コマンドを実行。

$ tar xvzf jo-1.1.tar.gz
$ cd jo-1.1
$ ./configure
$ make check
$ sudo make install

macOSならbrewでインストールできる。

$ brew install jo

コマンドヘルプ。

$ jo -v
jo 1.1
$ jo -help
Usage: jo [-a] [-B] [-p] [-v] [-V] [word...]
        word is key=value or key@value
        -a creates an array of words
        -B disable boolean true/false
        -p pretty-prints JSON on output
        -v show version
        -V show version in JSON

以下のようにkey=valueを指定してJSONオブジェクトを生成する。

$ jo name=jo n=17 parser=false
{"name":"jo","n":17,"parser":false}
$ jo -p name=jo n=17 parser=false
{
   "name": "jo",
   "n": 17,
   "parser": false
}
$ seq 1 10 | jo -a
[1,2,3,4,5,6,7,8,9,10]

jq

github.com

jqはJSONオブジェクトをフィルタ、整形するツール。
インストール方法はこのページを参照。

$ jq --help
jq - commandline JSON processor [version 1.5]
Usage: jq [options] <jq filter> [file...]

        jq is a tool for processing JSON inputs, applying the
        given filter to its JSON text inputs and producing the
        filter's results as JSON on standard output.
        The simplest filter is ., which is the identity filter,
        copying jq's input to its output unmodified (except for
        formatting).
        For more advanced filters see the jq(1) manpage ("man jq")
        and/or https://stedolan.github.io/jq

        Some of the options include:
         -c             compact instead of pretty-printed output;
         -n             use `null` as the single input value;
         -e             set the exit status code based on the output;
         -s             read (slurp) all inputs into an array; apply filter to it;
         -r             output raw strings, not JSON texts;
         -R             read raw strings, not JSON texts;
         -C             colorize JSON;
         -M             monochrome (don't colorize JSON);
         -S             sort keys of objects on output;
         --tab  use tabs for indentation;
         --arg a v      set variable $a to value <v>;
         --argjson a v  set variable $a to JSON value <v>;
         --slurpfile a f        set variable $a to an array of JSON texts read from <f>;
        See the manpage for more options.

有名なので使い方は他のページを参照。

echo '{"aa":"2AA2","bb":{"aaa":[123,"cccc",[1,2]],"c":321}}' | jq

f:id:wonder-wall:20180722211451p:plain

jid

github.com

jidjqのようなクエリでインタラクティブに絞り込めるツール。
インストールはReleases · simeji/jid · GitHubからファイルをダウンロードするか、macOSならbrewでインストール。

$ brew install jid

go getでもインストールできる。

$ go get -u github.com/simeji/jid/cmd/jid

コマンドヘルプ。

$ jid --version
jid version v0.7.2
$ jid --help


============ Load JSON from a file ==============

$ jid < file.json

============ With a JSON filter mode =============

TAB / CTRL-I
  Show available items and choice them

CTRL-W
  Delete from the cursor to the start of the word

CTRL-U
  Delete whole query

CTRL-F / Right Arrow
  Move cursor a character to the right

CTRL-B / Left Arrow
  Move cursor a character to the left

CTRL-A
  To the first character of the 'Filter'

CTRL-E
  To the end of the 'Filter'
  
CTRL-J
  Scroll json buffer 1 line downwards

CTRL-K
  Scroll json buffer 1 line upwards

CTRL-G
  Scroll json buffer to bottom

CTRL-T
  Scroll json buffer to top

CTRL-L
  Change view mode whole json or keys (only object)

ESC
  Hide a candidate box

jqと同じように絞り込める。タブを押せば候補が選択できるようになっている。

$ echo '{"aa":"2AA2","bb":{"aaa":[123,"cccc",[1,2]],"c":321}}'| jid

f:id:wonder-wall:20180722221544p:plain

f:id:wonder-wall:20180722221555p:plain

gron

github.com

gronはJSONオブジェクトをgrepできるようにするツール。
インストールはReleases · tomnomnom/gron · GitHubからファイルをダウンロードするか、macOSならbrewでインストール。

$ brew install gron

go getでもインストールできる。

$ go get -u github.com/tomnomnom/gron

コマンドヘルプ。

$ gron --version
gron version 0.6.0
$ gron --help
Transform JSON (from a file, URL, or stdin) into discrete assignments to make it greppable

Usage:
  gron [OPTIONS] [FILE|URL|-]

Options:
  -u, --ungron     Reverse the operation (turn assignments back into JSON)
  -c, --colorize   Colorize output (default on tty)
  -m, --monochrome Monochrome (don't colorize output)
  -s, --stream     Treat each line of input as a separate JSON object
  -k, --insecure   Disable certificate validation
  -j, --json       Represent gron data as JSON stream
      --no-sort    Don't sort output (faster)
      --version    Print version information

Exit Codes:
  0     OK
  1     Failed to open file
  2     Failed to read input
  3     Failed to form statements
  4     Failed to fetch URL
  5     Failed to parse statements
  6     Failed to encode JSON

Examples:
  gron /tmp/apiresponse.json
  gron http://jsonplaceholder.typicode.com/users/1
  curl -s http://jsonplaceholder.typicode.com/users/1 | gron
  gron http://jsonplaceholder.typicode.com/users/1 | grep company | gron --ungron

gronを使うと図のように1行に1つの値が出力されるのでgrepできるようになる。
gron -uを実行するとJSONオブジェクトに戻せる。

f:id:wonder-wall:20180722222208p:plain

jp

github.com

jpはJSONデータをターミナルでプロットするツール。
インストールはReleases · sgreben/jp · GitHubからからファイルをダウンロードするか、go getでインストール。

$ go get -u github.com/sgreben/jp/cmd/jp

コマンドヘルプ。

$ jp --help
Usage of ./jp:
  -bins uint
        Number of histogram bins (default 0 (auto))
  -canvas value
        Canvas type. One of [full full-escape full-bw full-wb quarter braille auto] (default auto)
  -height int
        Plot height (default 0 (auto))
  -input value
        Input type. One of [json csv] (default json)
  -type value
        Plot type. One of [line bar scatter hist hist2d] (default line)
  -width int
        Plot width (default 0 (auto))
  -x string
        x values (JSONPath expression)
  -xy string
        x,y value pairs (JSONPath expression). Overrides -x and -y if given.
  -y string
        y values (JSONPath expression)

図のような棒グラフの他にも折れ線グラフ、散布図、ヒストグラムのプロットもできる。

$ echo '[[-3, 5], [-2, 0], [-1, 0.1], [0, 1], [1, 2], [2, 3]]' | jp -xy '[*][0, 1]' -type bar

f:id:wonder-wall:20180722224644p:plain

json-server

github.com

json-serverはJSON形式のデータからAPIモックサーバを起動するツール。
npmでインストールできる。

$ npm install -g json-server

コマンドヘルプ。

$ json-server --version
0.14.0
$ json-server --help
json-server [options] <source>

Options:
  --config, -c               Path to config file   [default: "json-server.json"]
  --port, -p                 Set port                            [default: 3000]
  --host, -H                 Set host                     [default: "localhost"]
  --watch, -w                Watch file(s)                             [boolean]
  --routes, -r               Path to routes file
  --middlewares, -m          Paths to middleware files                   [array]
  --static, -s               Set static files directory
  --read-only, --ro          Allow only GET requests                   [boolean]
  --no-cors, --nc            Disable Cross-Origin Resource Sharing     [boolean]
  --no-gzip, --ng            Disable GZIP Content-Encoding             [boolean]
  --snapshots, -S            Set snapshots directory              [default: "."]
  --delay, -d                Add delay to responses (ms)
  --id, -i                   Set database id property (e.g. _id) [default: "id"]
  --foreignKeySuffix, --fks  Set foreign key suffix (e.g. _id as in post_id)
                                                                 [default: "Id"]
  --quiet, -q                Suppress log messages from output         [boolean]
  --help, -h                 Show help                                 [boolean]
  --version, -v              Show version number                       [boolean]

Examples:
  json-server db.json
  json-server file.js
  json-server http://example.com/db.json

https://github.com/typicode/json-server

以下のデータをdb.jsonというファイル名で用意。

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

次に下記コマンドでサーバを起動。

$ json-server --watch db.json

f:id:wonder-wall:20180722223400p:plain

以下のようにアクセスするとレスポンスが返ってくる。

$ curl http://localhost:3000/posts/1
{
  "id": 1,
  "title": "json-server",
  "author": "typicode"
}

json2csv

github.com

json2csvはJSONオブジェクトをCSV形式に変換するツール。
npmでインストールできる。

$ npm install -g json2csv

コマンドヘルプ。

$ json2csv --version
4.1.6
$ json2csv --help

  Usage: json2csv [options]

  Options:

    -V, --version                       output the version number
    -i, --input <input>                 Path and name of the incoming json file. If not provided, will read from stdin.
    -o, --output [output]               Path and name of the resulting csv file. Defaults to stdout.
    -n, --ndjson                        Treat the input as NewLine-Delimited JSON.
    -s, --no-streaming                  Process the whole JSON array in memory instead of doing it line by line.
    -f, --fields <fields>               Specify the fields to convert.
    -c, --fields-config <path>          Specify a file with a fields configuration as a JSON array.
    -u, --unwind <paths>                Creates multiple rows from a single JSON document similar to MongoDB unwind.
    -B, --unwind-blank                  When unwinding, blank out instead of repeating data.
    -F, --flatten                       Flatten nested objects
    -v, --default-value [defaultValue]  Specify a default value other than empty string.
    -q, --quote [value]                 Specify an alternate quote value.
    -Q, --double-quote [value]          Specify a value to replace double quote in strings
    -d, --delimiter [delimiter]         Specify a delimiter other than the default comma to use.
    -e, --eol [value]                   Specify an End-of-Line value for separating rows.
    -E, --excel-strings                 Converts string data into normalized Excel style data
    -H, --no-header                     Disable the column name header
    -a, --include-empty-rows            Includes empty rows in the resulting CSV output.
    -b, --with-bom                      Includes BOM character at the beginning of the csv.
    -p, --pretty                        Use only when printing to console. Logs output in pretty tables.
    -h, --help                          output usage information

入力として以下のjsonファイルを用意。

$ cat input.json
[
  { "carModel": "Audi",      "price": 0,  "color": "blue" },
  { "carModel": "BMW",       "price": 15000,  "color": "red", "transmission": "manual" },
  { "carModel": "Mercedes",  "price": 20000,  "color": "yellow" },
  { "carModel": "Porsche",   "price": 30000,  "color": "green" }
]

-pを指定すると見やすい形式で出力してくれる。

$ json2csv -i input.json -f carModel,price,color
"carModel","price","color"
"Audi",0,"blue"
"BMW",15000,"red"
"Mercedes",20000,"yellow"
"Porsche",30000,"green"
$ json2csv -i input.json -f carModel,price,color -p
┌────────────────────┬───────────────┬───────────────┐
│ "carModel"         │ "price"       │ "color"       │
├────────────────────┼───────────────┼───────────────┤
│ "Audi"             │ 0             │ "blue"        │
├────────────────────┼───────────────┼───────────────┤
│ "BMW"              │ 15000         │ "red"         │
├────────────────────┼───────────────┼───────────────┤
│ "Mercedes"         │ 20000         │ "yellow"      │
├────────────────────┼───────────────┼───────────────┤
│ "Porsche"          │ 30000         │ "green"       │
└────────────────────┴───────────────┴───────────────┘

jsondiffpatch

github.com

jsondiffpatchはJSONオブジェクトの差分を出力できるツール。
npmでインストールできる。

$ npm install -g jsondiffpatch

コマンドヘルプ。

$ jsondiffpatch --help

  USAGE: jsondiffpatch left.json right.json

icdiff(improved colored diff )との出力の違いは以下のようになる。

f:id:wonder-wall:20180722224626p:plain

wonderwall.hatenablog.com