larsmoa larsmoa - 2 months ago 9
JSON Question

Handling multiple "elements" in one JSON file with jq

I have a JSON-file which consists of multiple JSON-"elements", e.g.

{
"name": "Name 1",
"foo": "Bar"
}
{
"id": 123,
"bar": "Foo"
}


I'm only interested in the second element and I need to query by the 'index' of the element (i.e. I do not know what fields the element will contain).

How do I achieve this with
jq
?

Answer

There are several possible answers, depending on which version of jq you have, so here I'll focus on a generic and generally useful answer.

  1. Use the -s ("slurp") option to get the second JSON entity, as in jq -s '.[1]'

  2. In jq 1.4 and later, the jq filter .[] when used on objects preserves the order of the keys. (Using jq 1.3, you may be out of luck if you do not know anything about the key names.) For example, using jq 1.4 or later:

$ jq '.[]' {"b":1, "a":2} 1 2

Comments