skip to Main Content

I’m attempting to use jq to combine the data of many JSON files. However, most solutions I tried clobber the data and I end up losing most of it.

Each file looks something like this

{
  "Brand":"brand",
  "Fulfilled":5600,
  "Total":5626,
  "Data":[
    {
      "data":"data1"
    },
    {
      "data":"data2"
    }
  ]
}

I want to pull the contents from the main ‘Data’ array from each file and make it look something like this:

{
  "Everything":[
    {
      "data":"data1"
    },
    {
      "data":"data2"
    },
    {
      "data":"data3"
    },
    {
      "data":"data4"
    }
  ]
}

2

Answers


  1. You can use inputs in combination with the -n flag to address all input documents:

    jq -n '{Everything: [inputs.Data[]]}' *.json
    
    {
      "Everything": [
        {
          "data": "data1"
        },
        {
          "data": "data2"
        },
        {
          "data": "data3"
        },
        {
          "data": "data4"
        }
      ]
    }
    

    Demo

    Login or Signup to reply.
  2. If you use the -s switch, there will be an implicit array wrapping around all objects emitted by the *.json, and so you can also do this without having to explicitly reference the inputs object:

    § jq -s '{ Everything:[ .[].Data[] ] }' *.json
    {
      "Everything": [
        {
          "data": "data1"
        },
        {
          "data": "data2"
        },
        {
          "data": "data1"
        },
        {
          "data": "data2"
        }
      ]
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search