Search code examples
jsonbashopenwrt

Get key-value pairs from JSON on OpenWRT (bash)


I'm working on an OpenWRT project where I need to get data from a server. The data is in JSON format and looks something like this:

{"key1":"value1","key2":"value2","key3":"value3"}

I want to parse it to 2 arrays in bash, like this:

keys[0]=key1
keys[1]=key2
keys[2]=key3

values[0]=value1
values[1]=value2
values[2]=value3

I tired jshn.sh, but it only can extract values for known keys.


Solution

  • Using grep and tr:

    declare -a keys=($(grep -Eo '"\w+":' json | tr -d \":))
    declare -a values=($(grep -Eo ':"\w+"' json | tr -d \":))
    

    Output:

    $ for i in 0 1 2; do echo "${keys[$i]} - ${values[$i]}"; done
    key1 - value1
    key2 - value2
    key3 - value3
    

    In this case, I have assumed your JSON data is stored in a file named 'json' - this could be replaced with the output of a command like so:

    declare -a keys=($(grep -Eo '"\w+":' <(curl www.example.com/json?q=test) | tr -d \":))