jasonmclose
jasonmclose

Reputation: 1695

How to mix levels of json coming out of jq

So I am trying to pull out some JSON with jq.

Here is an example:

{     
    "limit":10,
    "offset":20,   
    "values": [
       {
          "id": "abcd"
          "type": "file"
          "users": {
             "total": 2, 
             "profiles": [
                {
                     "first_name": "John", 
                     "last_name": "Smith"
                },
                {
                     "first_name": "Sue", 
                     "last_name": "Johnson"
                }
             ]
          }
       },
       {
          "id": "efgh"
          "type": "folder"
          "users": {
             "total": 1, 
             "profiles": [
                {
                     "first_name": "Steve", 
                     "last_name": "Gold"
                }
             ]
          }
       },
    ] 
}

I would love to get the following in my result

limit:10
offset:20
id:abcd, type:file, [users.total:2, users.profiles.first_name: [John, Sue], users.profiles.last_name: [Smith, Johnson]], 
id:efgh, type:folder, [users.total:1, users.profiles.first_name: [Steve], users.profiles.last_name: [Gold]], 

I know I can pipe this to jq, but I don't know how. I can get stuff in an array easily, but I can't seem to figure out how to do it and add in the top level elements. So it's 'limit' and 'offset' that are throwing me fits.

I can get something out

jq ".values[] | .users.total, .users[].first_name, .users[].last_name"

But I cannot seem to figure out how to add in limit and offset.

Upvotes: 0

Views: 949

Answers (2)

peak
peak

Reputation: 116919

So it's 'limit' and 'offset' that are throwing me fits.

It looks like to_entries might be what you're looking for. Consider, for example:

to_entries[]
| select(.value | type != "array") 
| [.key, .value]
| join(": ")

With your JSON, this produces the lines you are having difficulty with, without any explicit mention of the key names:

limit: 10
offset: 20

You could then (for example) use the comma operator (,) to produce the other lines you want.

Upvotes: 0

Barmar
Barmar

Reputation: 782130

You can use commas at the top-level to get those fields. Use parentheses to group the expression that gets everything from .values.

jq '.limit, .offset, (.values[] | .id, .type, .users.total, .users.profiles[].first_name, .users.profiles[].last_name)'

DEMO

Upvotes: 3

Related Questions