Home > Back-end >  How to convert to json file
How to convert to json file

Time:11-12

I am writing a bash script utilizing to json

Example

This is my input file:

{
  "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"
}

I want to convert these into json like below

[
    {"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"}
]

Please let me know how to achieve this

CodePudding user response:

Luckily, jq, the de factor standard tool for working with JSON data in shell scripts, understands input files with multiple JSON values, instead of requiring only one value per file like some programs. Creating an array of objects using data from the input objects is trivial:

$ 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"
  }
]
  • Related