Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducing JSON with jq

Tags:

unix

jq

I have a JSON array of Objects:

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

I would like to reduce these into the following structure:

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

Is this possible to do with jq?

I was trying:

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

This doesn't quite work as it iterates over each datum rather than reducing it to one Object.

like image 945
turtle Avatar asked Apr 03 '14 14:04

turtle


People also ask

Can jq write JSON?

jq is an amazing little command line utility for working with JSON data. We've written before about how you can use jq to parse JSON on the command line, but in this post I want to talk about using jq to create JSON data from scratch or make changes to existing data.

Does jq use JSONPath?

jp is a JSON processor for the command line using JSONPath (aka "a simpler jq, and with JSONPath").

Is jq fast?

jq is very fast for coding simple, stateless pipelines. Any particular section can be tested by specifying the json value on stdin and looking at the json value on stdout.

What is jq slurp?

“Slurp” tells jq to read every line of the input JSON lines and treat the entire group as one huge array of objects. With the Twitter data still in the input box on jq play, check the “Slurp” box, and just put .


2 Answers

Note that jq has a builtin function called 'add' that the same thing that the first answer suggests, so you ought to be able to write:

jq add myjson.json
like image 108
user2259432 Avatar answered Oct 09 '22 21:10

user2259432


To expand on the other two answers a bit, you can "add" two objects together like this:

.[0] + .[1]

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

You can use the generic reduce function to repeatedly apply a function between the first two items of a list, then between that result and the next item, and so on:

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

We start with {}, add .[0], then add .[1] etc.

Finally, as a convenience, jq has an add function which is essentially an alias for exactly this function, so you can write the whole thing as:

add

Or, as a complete command line:

jq add myjson.json
like image 27
Steve Bennett Avatar answered Oct 09 '22 23:10

Steve Bennett