2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jqでhash操作(追加と削除)メモ

Posted at

##0. やりたいこと

  1. json形式のデータをスクリプトで処理するときに、key:valueのペアを追加する
  2. json形式のデータをスクリプトで処理するときに、key:valueのペアを削除する

##1. jsonのサンプルデータ

sample.json
{
  "ginza": {
    "foods": {
      "maindish": "sushi",
      "dessert": "warabimochi",
      "antipast": "anpan",
      "drink": "champagne"
    }
  }
}

##2. 追加

"aperitif":"soda"というkey valueペアをfoodsのハッシュに追加したいとき

cat sample.json | jq '.ginza.foods | .+ {"aperitif":"soda"}' 
{
  "maindish": "sushi",
  "dessert" : "warabimochi",
  "antipast": "anpan",
  "drink"   : "champagne",
  "aperitif": "soda"
}

##3. 削除

"drink" : "champagne"を削除してみる
keyがdrinkじゃない要素だけ表示する、みたいなロジック。

cat sample.json | jq '.ginza.foods | with_entries(select( .key != "drink"))'
{
  "maindish": "sushi",
  "dessert": "warabimochi",
  "antipast": "anpan"
}

こんな感じで使ってみた。
ただし、もっと良い方法あるかもです。

2
0
0

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?