dfstandish dfstandish - 3 months ago 6
JSON Question

access fields in json object with unique identifiers

I'm having trouble understanding jq. I'm even having trouble articulating what I want to learn.

I think I want a wildcard? my desire is, given a json snippet like this:

{
"logs": {
"-MnpQaRONGXz9tff-W": {
"points": 10,
"type": "signup"
},
"-N5qlX1mQ3SYA9RXdE": {
"points": 15,
"type": "welcome"
},
"-N5rx8PAcNgWu25zRf": {
"points": 5,
"type": "vote"
},
"-N5s29TyZ33snUqC5X": {
"points": 5,
"type": "vote"
}
},
"total": 35
}


Count how many times a certain type appears, or even just output all the types into a file.

This totally doesn't work (and in the simplified example doesn't make sense):

cat test.json | jq '.logs | * | .type'


would get me a simple object or listing of the types .

Answer

To obtain all the "type" values, the following would suffice:

.[] | select(type == "object") | .[].type

To produce a tabulation:

def tabulate: reduce .[] as $i ({}; .[$i] += 1 );

[.[] | select(type == "object") | .[].type] | tabulate

Given your input, the output would be: { "signup": 1, "welcome": 1, "vote": 2 }