LoginSignup
18
9

More than 5 years have passed since last update.

[ jq ] keyの値にドット(.)が入っているときはどうするか

Last updated at Posted at 2016-02-15

jqコマンドは便利です。もっと使いこなしたい。

0. 普通の使い方

こういうファイルがあったとする

testfile
{
  "result": {
    "hostname": {
      "testserverlocal": {
        "status": "fail"
      }
    }
  }
}

このようにjqコマンドを使うとstatusの値を取り出せる

cat testfile | jq .result.hostname.testserverlocal.status
=> "fail"

##あるいはrオプションでダブルクォーテーション消す
cat testfile | jq -r .result.hostname.testserverlocal.status
=> fail

1. keyにドット(.)があるときはどうする?

testfile02
{
  "result": {
    "hostname": {
      "test.server.local": {
        "status": "fail"
      }
    }
  }
}

この場合はcat testfile2 | jq .result.hostname.test.server.local.statusだとうまくいかない。マニュアルを読んでみた。このマニュアル(https://stedolan.github.io/jq/manual/ ) の中にこういう記述がある。

The .foo syntax only works for simply keys i.e. keys that are all alphanumeric characters. 
.[<string>] works with keys that contain special characters such as colons and dots. 
For example .["foo::bar"] and .["foo.bar"] work while .foo::bar and .foo.bar would not.

これによればcat testfile2 | jq .result.hostname.["test.server.local"].statusとすれば良いのかな?と思うが、やってみると失敗した。。。。その後ググったり試行錯誤をしてみた。結局下記のようにするとうまくいきました。他のやり方あればぜひ教えていただきたいです。。。(と書いたら情報をいただき大変感謝です)。

cat testfile2 | jq .result.hostname | jq '.["test.server.local"]'.status
=> "fail"

  • .["foo.bar"]ではなく'.["foo.bar"]'とする(シングルクォートで囲む)
  • ネストされているキーに対してこの手法は使えないのでjqをパイプでつないでみた。

2. 追記(いろいろな方法)

jq .result.hostname'["test.server.local"]'.statusと書く。
またはクエリ全体をシングルクォートで囲んでjq '.result.hostname["test.server.local"].status'と書く。
要するにhostnameというキーの要素を指定するときにドット(.)でつなげないで直接つなげる。
下記2種類のクエリ指定でどちらも同じ結果が返った。

cat testfile2 | jq '.result.hostname["test.server.local"].status'
=> "fail"

cat testfile2 | jq .result.hostname'["test.server.local"]'.status
=> "fail"


18
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
9