JSON reduction with jq

I have an array of JSON objects:

[{key1: value},{key2:value}, ...]

I would like to reduce them to the following structure:

{key1: value, key2: value, ...} 

Can this be done with jq ?

I have tried:

cat myjson.json | jq '.[] | {(.key): value}'

This does not work, because it iterates over each database, rather than reducing it to a single object.

+4
source share
3 answers

Note that jq has a built-in function called 'add', the same as the first answer suggests, so you should be able to write:

jq add myjson.json
+5
source

To expand the other two answers, you can “add” two objects together as follows:

.[0] + .[1]

=> { "key1": "value", "key2": "value" }

reduce , ..:

reduce .[] as $item ({}; . + $item)

{}, .[0], .[1] ..

, jq add, , :

add

, :

jq add myjson.json
+1

I believe the following will work:

cat myjson.json | jq 'reduce .[] as $item ({}; . + $item)'

It takes every element in the array and adds it to the sum of all previous elements.

0
source

Source: https://habr.com/ru/post/1534854/


All Articles