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

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

Last updated at Posted at 2018-07-04

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

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

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