Help us understand the problem. What is going on with this article?

jqコマンドでjsonデータを整形・絞り込み

jq コマンドでjsonデータを整形・絞り込みする方法

jqはJSON用のsedのようなコマンドでデータのフィルタや置き換え、整形ができます。

2014/04/10追記
コメントでpipeする際jqコマンドは不要と教えて頂きました。

インストール

homebrew でインストールできます。

brew install jq

他の方法はこちらを参照
http://stedolan.github.io/jq/download/

インデント

jqコマンドに渡すだけでインデントできる。

このようなデータがあったとして、

[{"name": "Ann", "age": 20},{"name": "Bob", "age": 50},{"name": "Unknown", "age": 45}]

jq コマンドに与えるとインデントして表示される。 . は すべてのデータを指す

echo '[{"name": "Ann", "age": 20},{"name": "Bob", "age": 50},{"name": "Unknown", "age": 45}]' | jq .  
[
  {
    "age": 20,
    "name": "Ann"
  },
  {
    "age": 50,
    "name": "Bob"
  },
  {
    "age": 45,
    "name": "Unknown"
  }
]

絞り込み

1つ目のデータを取得したい場合は . では無く .[0]を指定する

echo '[{"name": "Ann", "age": 20},{"name": "Bob", "age": 50},{"name": "Unknown", "age": 45}]' | jq '.[0]'       
{
    "age": 20,
    "name": "Ann"
}

age > 30 (31歳以上)を取得したいならmap , selectを使う

echo '[{"name": "Ann", "age": 20},{"name": "Bob", "age": 50},{"name": "Unknown", "age": 45}]' | jq 'map(select( .["age"] > 30))'    
[
  {
    "age": 50,
    "name": "Bob"
  },
  {
    "age": 45,
    "name": "Unknown"
  }
]

age > 30 のnameだけを取得したいときはさらに jqで絞り込み

echo '[{"name": "Ann", "age": 20},{"name": "Bob", "age": 50},{"name": "Unknown", "age": 45}]' | jq 'map(select( .["age"] > 30))' | jq '.[].name'
"Bob"
"Unknown"

jqの中でpipeさせることもできる。その場合はjqコマンドは1つでよい。

echo '[{"name": "Ann", "age": 20},{"name": "Bob", "age": 50},{"name": "Unknown", "age": 45}]' | jq 'map(select( .["age"] > 30)) | .[].name'

配列の長さを取りたいときは length を使う

echo '[{"name": "Ann", "age": 20},{"name": "Bob", "age": 50},{"name": "Unknown", "age": 45}]' | jq length  
3

参考

Nakau
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした