Jq: nested object, extracts the top-level identifier and raises the value from the internal object

Given the following xample.json ;

 [ { "id": 12345678, "stuff": { "book": "shelf", "hook": "line", "took": "off", "info-spec": 12 }, "votes": 23 }, { "id": 12345679, "stuff": { "book": "maker", "hook": "sinker", "took": "pisin", "info-spec": 23 }, "votes": 1 } ] 

I can easily extract id and votes :

 $ jq '.[] | { id, votes }' xample.json { "votes": 23, "id": 12345678 } { "votes": 1, "id": 12345679 } 

But what would the query look like for retrieving id and stuff.info-spec ? The obvious (for me) syntax doesn't work at all:

 $ jq '.[] | { id, stuff.info-spec }' xample.json error: syntax error, unexpected '.', expecting '}' .[] | { id, stuff.info-spec } ^ 1 compile error 

I tried stuff[info-spec] and stuff["info-spec"] , but I just can't imagine how to do it.

The silence in the key name seems to make things even more complicated, but my limited understanding is that I can get around this with double quotes.

 $ sed 's/votes/vo-tes/g' xample.json | jq '.[] | { id, "vo-tes" }' 

gives the expected result (ie the same as above without a dash in "vo-tes").

I can extract the book :

 $ jq '.[] | .stuff.book' xample.json 

but again can not understand the syntax of id and book ; but also I cannot extract info-spec with the same syntax:

 $ jq '.[] | .stuff."info-spec"' xample.json error: syntax error, unexpected QQSTRING_START, expecting IDENT .[] | .stuff."info-spec" ^ 1 compile error 

If I print quotes, an error message (maybe something else):

 $ jq '.[] | .stuff.info-spec' xample.json error: spec is not defined .[] | .stuff.info-spec ^^^^ 1 compile error 

But hey, this works:

 $ jq '.[] | .stuff["info-spec"] ' xample.json 12 23 

Then my desired result for this example

 { "info-spec": 12, "id": 12345678 } { "info-spec": 23, "id": 12345679 } 

I looked at the FAQ and jq Cookbook , but I can not find anything about the syntax for "lifting" an object inside an object inside another object.

+7
json bash jq
source share
2 answers

I managed to figure it out.

 $ jq '.[] | { id, "info-spec": .stuff["info-spec"] }' xample.json { "info-spec": 12, "id": 12345678 } { "info-spec": 23, "id": 12345679 } 

The key point here is to use the newkey: .complex["key"] notation newkey: .complex["key"] to lift.

+1
source share

Interestingly, the problem is really a "-" character, and this works for me:

 jq '.[] | { id, "info-spec": .stuff."info-spec" }' xample.json { "id": 12345678, "info-spec": 12 } { "id": 12345679, "info-spec": 23 } 

but your jq doesn't seem to look like this syntax as it broke into the following, and I don't:

 jq '.[] | .stuff."info-spec"' xample.json 12 23 

I use:

 jq --version jq-1.4 

edit: looks like a problem with version 1.4: https://github.com/stedolan/jq/issues/38

+5
source share

All Articles