0

I am trying to flatten and re-transform a JSON payload via JQ, but have been unsuccessful thus far. I have the following payload that has a dynamic number of values depending for each object underneath the stats field:

{
  "stats": [
    {
      "devid": 3,
      "key": "diskall",
      "value": [
        {
          "0": 0.0001,
          "1": 0.0001,
          "2": 0.0012,
          "3": 0.0005,
          "4": 0.0007,
          "5": 0.0013,
          "6": 0.0006000000000000001,
          "7": 0.0006000000000000001,
          "8": 0.0006000000000000001,
          "9": 0.0006000000000000001,
          "10": 0.0005,
          "11": 0.0005,
          "12": 0.0005
        }
      ]
    },
    {
      "devid": 7,
      "key": "diskall",
      "value": [
        {
          "0": 0.0003,
          "1": 0.0004,
          "2": 0.0012,
          "3": 0.0005,
          "4": 0.0007,
          "5": 0.0013,
          "6": 0.00060001
        }
      ]
    }
  ]
}

I want to flatten and transform the value array object keys/values to a result like below (for each value within each stat object). Basically take the key in values and place that in a field called nodeId and take the value and place that in a field called value

{
"devid": 3
"key": "diskall"
"nodeId": 0
"value": 0.0001
},
{
"devid": 3
"key": "diskall"
"nodeId": 1
"value": 0.0001
},
{
"devid": 3
"key": "diskall"
"nodeId": 2
"value": 0.0012
},
{
"devid": 7
"key": "diskall"
"nodeId": 0
"value": 0.0003
}

I was able to flatten with jq like this: .stats | map(del(.value) + .value[]), but I'm not sure how to approach transforming the values into their own objects as well as rename the keys/values a bit.

0

1 Answer 1

1
.stats[]
| {devid,key} + (.value[] | to_entries[] | {nodeId: .key|tonumber, value})

You might wish to replace tonumber by (tonumber? // .) for robustness.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.