skip to Main Content

here is original json example:

{
  "item1": {
    "foo1": 1,
    "foo2": 2
},
  "item2": {
    "foo1": 11,
    "foo2": 22
  }
}

how can i convert it into json array with new attribute using jq:

[
  {
    "name": "item1",
    "foo1": 1,
    "foo2": 2
  },
  {
    "name": "item2",
    "foo1": 11,
    "foo2": 22
  }
]

also, it’s very interesting, how opposite conversion can be done as well!

thanks in advance!

i have been trying different approaches using "keys" and "keys_unsorted", but never got it work ((

2

Answers


  1. . as $arr | $arr
    | keys                        # Get all keys (names) of the array
    | map_values(
        . as $item | {
            item,                 # Preserve the original item
            attribute: $item | keys # Move name to "attribute" property
        }
    )
    
    Login or Signup to reply.
  2. Instead of keys I would start with to_entries:

    to_entries | map({name: .key} + .value)
    

    (online demo)

    The reverse then is

    map({key: .name, value: del(.name)}) | from_entries
    

    (online demo)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search