Nic
Nic

Reputation: 461

JQ: add nested object with name of top-level key

In my input in JQ 1.4...

{
    "key x": {
        "b": "1"
    },
    "key y": {
        "b": "1"
    }
}

...should add new nested objects under each top-level key with the name of its top-level key. So the result looks like

{
    "key x": {
        "a": "key x",
        "b": "1"
    },
    "key y": {
        "a": "key y",
        "b": "1"
    }
}

But without using the key names (e.g. ."key x".a="key x") directly, because i dont know during runtime the real key names.

Upvotes: 1

Views: 1771

Answers (2)

user3899165
user3899165

Reputation:

A simple answer would be:

with_entries(.value.a = .key)

Upvotes: 3

Nic
Nic

Reputation: 461

Yeah, found solution:

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

will return

{
  "key x": {
    "a": "key x",
    "b": "1"
  },
  "key y": {
    "a": "key y",
    "b": "1"
  }
}

to_entries splits to key/value pairs what is much easier to access each key and extend its value by new object.

Upvotes: 0

Related Questions