Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

コマンドラインでjsonの中身を書き換える

More than 1 year has passed since last update.

コマンドラインから、要素の追加をし、かきかえたい。

article.json
"newslist": [
  {
      "name": "test",
      "link": "test.pdf",
      "category": "飲食",
      "filesize": "0.4MB",
      "src": "news/news1808_insyoku.png?20180704",
      "srcset": "news/news1808_insyoku.png?20180704"
    },
]

要素の中に追加

|= .+をつけると要素の中が更新、または追加

(JSON='articles.json'; cat $JSON | jq '.newslist[0] |= .+ {"name": "myId"}' > 'articles.json') 

結果 (nameが更新される)

article.json
"newslist": [
  {
      "name": "myId",
      "link": "test.pdf",
      "category": "飲食",
      "filesize": "0.4MB",
      "src": "news/news1808_insyoku.png?20180704",
      "srcset": "news/news1808_insyoku.png?20180704"
    },
]

新しい要素として追加

newlistとつけたリスト[{"name": "myId"}]に変更で、新しい要素として追加

(JSON='articles.json'; add_json=`cat $JSON | jq '.newslist[]' | head -n 40`; cat $JSON | jq '.newslist |= .+ [{"name": "myId"}]' > 'new_json.json')

結果 (別の要素にnameが追加)

article.json
"newslist": [
    {
      "name": "myId"
    },
    {
      "name": "test",
      "link": "test.pdf",
      "category": "飲食",
      "filesize": "0.4MB",
      "src": "news/news1808_insyoku.png?20180704",
      "srcset": "news/news1808_insyoku.png?20180704"
    },
]

その他

jq '.newslist[] = {"name": "myId"}' #newslist全てに適応
jq '.newslist[0] = {"name": "myId"}' #newslistの0番目の要素にのみ
jq '.newslist = {"name": "myId"}' #newslistを上書き

参考

https://dev.classmethod.jp/tool/jq-manual-japanese-translation-roughly/
https://qiita.com/daikumatan/items/a4d872538a6857b89725#%E9%85%8D%E5%88%97%E3%81%AE%E8%A6%81%E7%B4%A0%E3%82%92%E8%BF%BD%E5%8A%A0-1

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