0

I would like to convert JSON string into "key=value" format separated by commas.

{"foo": "bar", "number": 123}

Should be converted into

foo=bar, number=123

I've been looking for jq documentation and searching for a simple solution but I'm having a hard time to achieve this dynamically, without knowing the names of the fields before hand.

This is furthest I've gotten to but I'm not sure how to fix the escaping issue and the code is pretty ugly.

04:52:32 root@raspberrypi ~ → echo $json
{"time_utc":1606488980,"Temperature":-0.3,"Humidity":100,"min_temp":-1.4,"max_temp":-0.2,"date_max_temp":1606476880,"date_min_temp":1606428232,"temp_trend":"stable"}
04:52:34 root@raspberrypi ~ → keys=$(echo $json | jq keys | jq -r .[] | awk '{printf $1"=\(."$1") "}')
04:52:41 root@raspberrypi ~ → echo $keys
Humidity=\(.Humidity) Temperature=\(.Temperature) date_max_temp=\(.date_max_temp) date_min_temp=\(.date_min_temp) max_temp=\(.max_temp) min_temp=\(.min_temp) temp_trend=\(.temp_trend) time_utc=\(.time_utc)
04:52:45 root@raspberrypi ~ → echo $json | jq -r "$keys"
jq: error: syntax error, unexpected INVALID_CHARACTER (Unix shell quoting issues?) at <top-level>, line 1:
Humidity=\(.Humidity) Temperature=\(.Temperature) date_max_temp=\(.date_max_temp) date_min_temp=\(.date_min_temp) max_temp=\(.max_temp) min_temp=\(.min_temp) temp_trend=\(.temp_trend) time_utc=\(.time_utc)          
jq: 1 compile error
04:53:17 root@raspberrypi ~ → echo $json | jq -r '"Humidity=\(.Humidity) Temperature=\(.Temperature) date_max_temp=\(.date_max_temp) date_min_temp=\(.date_min_temp) max_temp=\(.max_temp) min_temp=\(.min_temp) temp_trend=\(.temp_trend) time_utc=\(.time_utc)"'
Humidity=100 Temperature=-0.3 date_max_temp=1606476880 date_min_temp=1606428232 max_temp=-0.2 min_temp=-1.4 temp_trend=stable time_utc=1606488980
Joonas Alhonen
  • 322
  • 1
  • 11

1 Answers1

3
to_entries | map(join("=")) | join(", ")
  1. to_entries produces a list of key/value pairs e.g, [["foo","bar"], ...]
  2. join each pair with "=" e.g. ["foo=bar", ...]
  3. join each pair again with ", " e.g. "foo=bar, ...
customcommander
  • 17,580
  • 5
  • 58
  • 84
  • 1
    `echo $json | jq -r 'to_entries | map(join("=")) | join(", ")'` `jq: error (at :1): string ("=") and number (1606488980) cannot be added` This looks like a very clean solution but I'm getting the error above. Seems like it's trying to set "=" as a key? – Joonas Alhonen Nov 27 '20 at 17:40
  • 1
    `jq 'map_values(tostring) | to_entries | map(join("=")) | join(", ")'` seems to work! – Joonas Alhonen Nov 27 '20 at 17:56
  • In jq 1.5 and later, join/1 does scalar-to-string conversions as required. – peak Nov 27 '20 at 23:31