Dave Gray
Dave Gray

Reputation: 723

transforming a nested json object

I have a nested json object like so:

{
  "results": {
    "category_a": {
      "types": {
        "type_a": {},
        "type_b": {},
        "type_c": {}
      }
    },
    "category_b": {
      "types": {
        "type_y": {},
        "type_z": {}
      }
    }
  }
}

and I'd like to squash it down it into a simpler nested object:

{
  "category_a": [
    "type_a",
    "type_b",
    "type_c"
  ],
  "category_b": [
    "type_y",
    "type_z"
  ]
}

This is what I have so far, which is close to what I want:

.results
| to_entries[]
| {
    (.key): [
      .value.types | keys[]
    ]
  }

except that the output is line-oriented instead of being a single object:

{
  "category_a": [
    "type_a",
    "type_b",
    "type_c"
  ]
}
{
  "category_b": [
    "type_y",
    "type_z"
  ]
}

How can I combine those two json objects into one? Do I need to approach the transformation differently?

Upvotes: 1

Views: 139

Answers (1)

peak
peak

Reputation: 116949

Working with your program as a starting point, you can simply wrap the separate objects in square brackets, and then use add:

.results
| [to_entries[] | { (.key): [ .value.types | keys[] ] } ]
| add

Upvotes: 1

Related Questions