jqlang / jq

Command-line JSON processor
https://jqlang.github.io/jq/
Other
30.52k stars 1.58k forks source link

QUESTION: A way to concatenate input objects into one #70

Closed gustaff-weldon closed 11 years ago

gustaff-weldon commented 11 years ago

Is there way to to take an array of objects and produce one object as a result? input:

[
 { "id" : "key1", "value" : "value1" },
 { "id" : "key2", "value" : "value2" }
]

And I would like to transform this output into

{
   "key1": "value1",
   "key2": "value2"
}

I can get a set of objects by using

jq ".[] | { (.id): .value} "

but that's not what I want.

Is there a way to use + to merge with last result? Or just to back-reference last result somehow? Or maybe a {} syntax similar to creating an array by surrounding whole expression eg.

jq "{ .[] |  (.id): .value } "

I have also tried abusing = operator (jq ".[] | (.id)= .value ", but it did not yield usable results. Any help would be appreciated.

stedolan commented 11 years ago

I'm assuming you meant {"key1": "value1", "key2": "value2"} as the desired output (can't repeat keys in JSON).

jq's + and add functions (+ takes two arguments, add takes an array and adds them all up) can merge objects. So, you first need to convert it into a list of objects with one key-value entry each, then add them together.

jq 'map({(.id): .value}) | add'
gustaff-weldon commented 11 years ago

Yes, sorry for the copy-paste error, fixed that one. Thanks, for the answer.

mailsanchu commented 3 years ago

My scenario is slightly different. Keys are dynamic [ { "100": "ONE", "200": "TWO" }, { "100": "1", "200": "2" } ] My expected output is{"1":"ONE","2":"TWO"}. How can I write an jq expresssion