#
ドキュメント

Document

自分のための備忘録です。

jq

Ref.

rオプション

キー、値のダブルクォーテーションを削除(-r--raw-output)。

配列

sample.json

{
  "objects": [
    {
      "name": "foo"
    },
    {
      "name": "bar"
    }
  ]
}
$ cat sample.json | jq '.objects'

[
  {
    "name": "foo"
  },
  {
    "name": "bar"
  }
]
$ cat sample.json | jq '.objects[]'

{
  "name": "foo"
}
{
  "name": "bar"
}
$ cat sample.json | jq '.objects[].name'

"foo"
"bar"

複数のプロパティ

sample.json

{
  "objects": [
    {
      "name": "foo",
      "age": 28,
      ..........,
      ..........
    },
    {
      "name": "bar"
      "age": 30,
      ..........,
      ..........
    }
  ]
}
$ cat sample.json | jq '.objects[] | .name, .age'

"foo"
28
"bar"
30

サイズ

sample.json

{
  "objects": [
    {
      "key1": "foo"
    },
    {
      "key1": "bar",
      "key2": "baz"
    }
  ]
}

```sh
$ cat sample.json | jq '.objects | length'

2
``

```sh
$ cat sample.json | jq '.objects[] | length'

1
2

キーが2つ以上のオブジェクトを取り出す。

$ cat sampe.json | jq '.objects[] | .size = length | select(.size > 1)'

{
  "key1": "bar",
  "key2": "baz",
  "size": 2
}

日付比較

{
  "objects": [
    {
      "key1": "foo",
      "date": "2023-01-06T04:16:14.862Z"
    },
    {
      "key1": "bar",
      "key2": "baz",
      "date": "2022-12-31T04:16:14.862Z"
    }
  ]
}
$ cat sample.json | jq '.objects[] | select(.date > "2023-01-01") | .key1'

"foo"

ref.

文字列結合

sample.json

{
  "objects": [
    {
      "key1": "foo",
      "date": "2023-01-06T04:16:14.862Z"
    },
    {
      "key1": "bar",
      "key2": "baz",
      "date": "2022-12-31T04:16:14.862Z"
    }
  ]
}
$ cat sample.json | jq -r '.objects[] | .key1 +"!!", .date'
foo!!
2023-01-06T04:16:14.862Z
bar!!
2022-12-31T04:16:14.862Z

## 存在しないプロパティ( null )を除外

{
  "objects": [
    {
      "name": "foo",
      "age": 28,
      ..........,
      ..........
    },
    {
      "name": "bar"
      ..........,
      ..........
    }
  ]
}
$ cat sample.json | jq '.objects[] | select(.age != null) | .name, .age'

"foo",
28
``

## 正規表現検索

sample.json

```json
{
  "objects": [
    {
      "key1": "foo",
      "date": "2023-01-06T04:16:14.862Z"
    },
    {
      "key1": "bar",
      "key2": "baz",
      "date": "2022-12-31T04:16:14.862Z"
    }
  ]
}
$ cat sample.json | jq -r '.objects[] | select(.key1 | test("^f")) | .key1, .date'
foo
2023-01-06T04:16:14.862Z

正規表現置換

$ jq -r '.objects[] | .key1 | sub("^f"; "F")'
Foo
bar

キー追加

$ cat sample-data.json | jq -r '.objects[] | .additional = .key1 + .date'
{
  "key1": "foo",
  "date": "2023-01-06T04:16:14.862Z",
  "additional": "foo2023-01-06T04:16:14.862Z"
}
{
  "key1": "bar",
  "key2": "baz",
  "date": "2022-12-31T04:16:14.862Z",
  "additional": "bar2022-12-31T04:16:14.862Z"
}