環境
macOS 10.12.6
前提
例えばこのような整形されてない1行のjsonがあったとする
{"_id":"5b741173880fca45bc090db0","index":0,"guid":"bf4b9d4b-4016-4ac3-aca0-5202b1f714cc","isActive":false,"balance":"$2,379.87","picture":"http://placehold.it/32x32","age":39,"eyeColor":"blue","name":"Wynn Ramos","gender":"male","company":"UNI","email":"wynnramos@uni.com","phone":"+1 (889) 522-3786","address":"518 Martense Street, Bloomington, New Jersey, 7440"}
自分の場合、Android StudioのLogcatに出力された1行のjsonを整形して確認したい事があった
AtomやVScodeのJson整形プラグインを使ってもいいが、CLIでやってみる。
方法1 jq
ターミナルで以下コマンドにjsonを貼り付けて実行
jq . <<< 'ここにjson'
実際にやってみる
jq . <<< '{"_id":"5b741173880fca45bc090db0","index":0,"guid":"bf4b9d4b-4016-4ac3-aca0-5202b1f714cc","isActive":false,"balance":"$2,379.87","picture":"http://placehold.it/32x32","age":39,"eyeColor":"blue","name":"Wynn Ramos","gender":"male","company":"UNI","email":"wynnramos@uni.com","phone":"+1 (889) 522-3786","address":"518 Martense Street, Bloomington, New Jersey, 7440"}'
このように整形されて表示される
{
"_id": "5b741173880fca45bc090db0",
"index": 0,
"guid": "bf4b9d4b-4016-4ac3-aca0-5202b1f714cc",
"isActive": false,
"balance": "$2,379.87",
"picture": "http://placehold.it/32x32",
"age": 39,
"eyeColor": "blue",
"name": "Wynn Ramos",
"gender": "male",
"company": "UNI",
"email": "wynnramos@uni.com",
"phone": "+1 (889) 522-3786",
"address": "518 Martense Street, Bloomington, New Jersey, 7440"
}
出力結果もカラーリングされて見やすいのが素晴らしい
<<<とは
bashのヒアストリングという手法らしい
単コマンドへ文字列を渡す事ができるようだ
方法2 python
macなら最初からpythonが入ってるしね
echo 'ここにjson' | python -m json.tool
echo '{"_id":"5b741173880fca45bc090db0","index":0,"guid":"bf4b9d4b-4016-4ac3-aca0-5202b1f714cc","isActive":false,"balance":"$2,379.87","picture":"http://placehold.it/32x32","age":39,"eyeColor":"blue","name":"Wynn Ramos","gender":"male","company":"UNI","email":"wynnramos@uni.com","phone":"+1 (889) 522-3786","address":"518 Martense Street, Bloomington, New Jersey, 7440"}' | python -m json.tool
{
"_id": "5b741173880fca45bc090db0",
"index": 0,
"guid": "bf4b9d4b-4016-4ac3-aca0-5202b1f714cc",
"isActive": false,
"balance": "$2,379.87",
"picture": "http://placehold.it/32x32",
"age": 39,
"eyeColor": "blue",
"name": "Wynn Ramos",
"gender": "male",
"company": "UNI",
"email": "wynnramos@uni.com",
"phone": "+1 (889) 522-3786",
"address": "518 Martense Street,
備考
How can I pretty-print JSON in a (Unix) shell script? - Stack Overflow https://stackoverflow.com/questions/352098/how-can-i-pretty-print-json-in-a-unix-shell-script
JSON Generator – Tool for generating random data https://www.json-generator.com/