簡體   English   中英

如何轉換為json文件

[英]How to convert to json file

我正在編寫一個使用 json 的 bash 腳本

例子

這是我的輸入文件:

{
  "action_name": "pushed to",
  "created_at": "2021-11-04T07:49:43.553Z",
  "author": {
    "name": "Foo Name",
    "username": "foo"
  },
  "push_data": {
    "action": "pushed",
    "ref": "master",
    "commit_title": "#152069 Update foo"
  },
  "author_username": "foo"
}
{
  "action_name": "pushed to",
  "created_at": "2021-11-04T07:48:12.211Z",
  "author": {
    "name": "Bar Name",
    "username": "bar"
  },
  "push_data": {
    "action": "pushed",
    "ref": "feature/dev",
    "commit_title": "#152069 Update bar"
  },
  "author_username": "bar"
}

我想將這些轉換為 json,如下所示

[
    {"created_at": "2021-11-04T07:49:43.553Z", "action_name": "pushed to", "name": "Foo Name", "ref": "master", "commit_title": "#152069 Update foo"},
    {"created_at": "2021-11-04T07:48:12.211Z", "action_name": "pushed to", "name": "Bar Name", "ref": "feature/dev", "commit_title": "#152069 Update bar"}
]

請讓我知道如何實現這一目標

幸運的是, jq是在 shell 腳本中處理 JSON 數據的實際標准工具,它理解具有多個 JSON 值的輸入文件,而不是像某些程序那樣每個文件只需要一個值。 使用來自輸入對象的數據創建對象數組很簡單:

$ jq -n '[ inputs | { created_at, action_name, name: .author.name, ref: .push_data.ref,
                      commit_title: .push_data.commit_title } ]' input.json
[
  {
    "created_at": "2021-11-04T07:49:43.553Z",
    "action_name": "pushed to",
    "name": "Foo Name",
    "ref": "master",
    "commit_title": "#152069 Update foo"
  },
  {
    "created_at": "2021-11-04T07:48:12.211Z",
    "action_name": "pushed to",
    "name": "Bar Name",
    "ref": "feature/dev",
    "commit_title": "#152069 Update bar"
  }
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM