skip to Main Content

My input data looks like this

{
  "objects": [
    {
      "statistics": [
        {
          "dataType": 0,
          "value": 0.0,
          "id": 18
        },
        {
          "dataType": 1,
          "value": 0,
          "id": 89
        },
        {
          "dataType": 0,
          "value": 35.0,
          "id": 91
        },
        {
          "dataType": 0,
          "value": 33.0,
          "id": 20
        }
      ],
      "key": "gate01"
    },
    {
      "statistics": [
        {
          "dataType": 0,
          "value": 1.0,
          "id": 18
        },
        {
          "dataType": 1,
          "value": 24290.0,
          "id": 89
        },
        {
          "dataType": 0,
          "value": 110.0,
          "id": 91
        },
        {
          "dataType": 0,
          "value": 97.0,
          "id": 20
        }
      ],
      "key": "gate02"
    }
  ]
}

I would like to format this way

{
  "gate01": {
    "18": 0.0,
    "89": 0.0,
    "91": 35.0,
    "20": 33.0
  },
  "gate02": {
    "18": 1.0,
    "89": 24290.0,
    "91": 110.0,
    "20": 97.0
  }
}

I tried with this but it’s not working and I’m stuck

| jq '.objects[] | {(.key): {(.statistics[].id|tostring): .statistics[].value}}'

2

Answers


  1. You were close, you should expand .statistics only once like so:

    .objects | map({(.key): (.statistics | map({(.id | tostring): .value}) | add)}) | add
    

    Online demo

    Login or Signup to reply.
  2. This should achieve what you expected :

    jq '.objects |
        map({key, value: (.statistics | 
                          map({value, key:.id|tostring}) |
                          from_entries)
          }) |
        from_entries' input.json
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search