LoginSignup
9
5

More than 5 years have passed since last update.

jqを使って、jsonのarrayに要素追加/削除

Last updated at Posted at 2016-09-28

0. ファイル

  • 対象ファイル(external-scripts.json)
[
  "hubot-diagnostics",
  "hubot-help",
  "hubot-heroku-keepalive",
  "hubot-google-images",
  "hubot-google-translate",
  "hubot-pugme",
  "hubot-maps",
  "hubot-redis-brain",
  "hubot-rules",
  "hubot-shipit"
]

1. 追加

  • 配列の最後尾に要素追加
  • 配列の要素数もjqで取得して使う
 cat external-scripts.json | jq ".[$(cat external-scripts.json | jq '. | length')]|= .+\"hoge\""
[
  "hubot-diagnostics",
  "hubot-help",
  "hubot-heroku-keepalive",
  "hubot-google-images",
  "hubot-google-translate",
  "hubot-pugme",
  "hubot-maps",
  "hubot-redis-brain",
  "hubot-rules",
  "hubot-shipit",
  "hoge"          # <= 最後にhogeが追加された
]

# 追記: これでもできますが後からためしてみると、もっと簡単にできそうです
jq '.+["hohe"]' external-scripts.json  # とか
cat external-scripts.json | jq '.|=.+["hoge"]' # とか

2. 削除

  • hubot-heroku-keepaliveを配列から削除して表示してみる
 cat external-scripts.json | jq ' .-["hubot-heroku-keepalive"]' 
[
  "hubot-diagnostics",
  "hubot-help",
  "hubot-google-images",
  "hubot-google-translate",
  "hubot-pugme",
  "hubot-maps",
  "hubot-redis-brain",
  "hubot-rules",
  "hubot-shipit",     
]
  • hubot-shipithubot-pugmeを配列から削除して表示してみる
 cat external-scripts.json | jq ' .-["hubot-pugme","hubot-shipit"]' 
[
  "hubot-diagnostics",
  "hubot-help",        
  "hubot-google-images",
  "hubot-google-translate",
  "hubot-maps",
  "hubot-redis-brain",
  "hubot-rules"     
]
9
5
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
9
5