Jsonfilter: How to get the n-th node of a json struct?


this may seem like a dumb question, but I have tried many expressions that didn't yield what I was looking for.

Take for example the output of

ubus call network.wireless status

where you get nodes with the name of the wifi devices (e.g. "radio0" and "radio1"):

        "radio0": {
	"radio1": {

If you don't know the names of the nodes, how can you select the n-th (first, second, etc.) node on that level?
If I'm looking at deeper nested child nodes, this is easy. These two commands would, for example, return the first and second interface configured on radio1:

ubus call network.wireless status | jsonfilter -e "@.radio1.interfaces[0]"     # first interface on radio1
ubus call network.wireless status | jsonfilter -e "@.radio1.interfaces[1]"     # second interface on radio1

But I couldn't figure out, how to select the elements on the level of "radio0", "radio1", etc. Expressions like @[0] and many other variations I tried, didn't work.

As an alternative: Is there a way to just get the names of the nodes, so I can select them individually by name?



If you have a recent version of jsonfilter installed, you can abuse the implicit array mode to achieve something similar:

ubus call network.wireless status | jsonfilter -e '@[*]' | jsonfilter -a -e '@[1]'

The first jsonfilter call will output one radio JSON structure object per line, the second call then consumes this lines while using the -a flag to treat them like an array, this allows you to select the first or second radio regardless of the name.

1 Like

I don’t know jsonfilter, but I used jshn and loops of json_select, json_get_keys, for key in keys etc.

This isn’t a one line solution though.

1 Like

Thanks. I don't have a recent jsonfilter version yet, as I'm still on the LEDE 17.01 branch, but I can compile myself a new version soon enough.

I didn't know the jshn binary and shell library yet, but they do the job just fine for now (until I can use a newer jsonfilter version).

It's actually not that complicated to get the keys of the first level objects with jshn.sh:

. /usr/share/libubox/jshn.sh
json_load "$(ubus call network.wireless status)"
json_get_keys my_variable
# $my_variable now holds the names of the first level keys


1 Like