Json parsing question

Hello,

I need some help with parsing json. I need pairs of address and port (4th and 6th elements of command) from this:

SG-135 in /tmp # ubus call service list "{ 'verbose': true, 'name': '$packageName' }"
{
	"https-dns-proxy": {
		"instances": {
			"instance1": {
				"running": true,
				"pid": 13661,
				"command": [
					"/usr/sbin/https-dns-proxy",
					"-r",
					"https://private.canadianshield.cira.ca/dns-query",
					"-a",
					"127.0.0.1",
					"-p",
					"5053",
					"-b",
					"149.112.121.10,149.112.122.10",
					"-4",
					"-u",
					"nobody",
					"-g",
					"nogroup"
				]
			},
			"instance2": {
				"running": true,
				"pid": 13662,
				"command": [
					"/usr/sbin/https-dns-proxy",
					"-r",
					"https://cloudflare-dns.com/dns-query",
					"-a",
					"127.0.0.1",
					"-p",
					"5054",
					"-b",
					"1.1.1.1,1.0.0.1",
					"-4",
					"-u",
					"nobody",
					"-g",
					"nogroup"
				]
				}
			}
		}
	}
}

Condensed for brevity, I have this very inelegant piece of code:

		. /usr/share/libubox/jshn.sh
		ubusJson="$(ubus call service list "{ 'verbose': true, 'name': '$packageName' }")"
		json_init
		json_load "$ubusJson"
		json_select "$packageName"
		json_select instances
		json_get_keys index
		for i in $index; do
			address="$(jsonfilter -s "$ubusJson" -e "@['$packageName'].instances['$i'].command[4]")"
			port="$(jsonfilter -s "$ubusJson" -e "@['$packageName'].instances['$i'].command[6]")"
			echo "$address#$port"
		done

I couldn't figure out a way to get just the keys/index with jsonfilter and I'd prefer not to use /usr/share/libubox/jshn.sh at all rather than use its json_for_each_item.

Any suggestions?

root@er-x:~# cat /tmp/service-output.json 
{
	"https-dns-proxy": {
		"instances": {
			"instance1": {
				"running": true,
				"pid": 13661,
				"command": [
					"/usr/sbin/https-dns-proxy",
					"-r",
					"https://private.canadianshield.cira.ca/dns-query",
					"-a",
					"127.0.0.1",
					"-p",
					"5053",
					"-b",
					"149.112.121.10,149.112.122.10",
					"-4",
					"-u",
					"nobody",
					"-g",
					"nogroup"
				]
			},
			"instance2": {
				"running": true,
				"pid": 13662,
				"command": [
					"/usr/sbin/https-dns-proxy",
					"-r",
					"https://cloudflare-dns.com/dns-query",
					"-a",
					"127.0.0.1",
					"-p",
					"5054",
					"-b",
					"1.1.1.1,1.0.0.1",
					"-4",
					"-u",
					"nobody",
					"-g",
					"nogroup"
				]
				}
			}
		}
	}
}
root@er-x:~# cat /tmp/service-output.json | jsonfilter -F ': ' -e 'TUPLES=@[*].instances[*].command[4,6]' 
export TUPLES='127.0.0.1':'5053'\ '127.0.0.1':'5054'; 
root@er-x:~# eval $(cat /tmp/service-output.json | jsonfilter -F ': ' -e 'TUPLES=@[*].instances[*].command[4,6]')
root@er-x:~# for addrport in $TUPLES; do echo "item=$addrport"; done
item=127.0.0.1:5053
item=127.0.0.1:5054
root@er-x:~# 
1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.