Differences
This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision Next revision | Previous revision | ||
| docs:guide-developer:jshn [2023/08/26 15:10] – add json_get_vars stokito | docs:guide-developer:jshn [2024/08/03 12:52] (current) – [See also] stokito | ||
|---|---|---|---|
| Line 75: | Line 75: | ||
| ==== More complicated examples ==== | ==== More complicated examples ==== | ||
| + | === Parse file example === | ||
| Given the file: | Given the file: | ||
| <code - / | <code - / | ||
| Line 105: | Line 105: | ||
| </ | </ | ||
| - | Parse arrays | + | === Parse arrays |
| + | |||
| + | Given the file: | ||
| <code - / | <code - / | ||
| { | { | ||
| Line 126: | Line 128: | ||
| then | then | ||
| json_select lan | json_select lan | ||
| - | idx=1 | + | idx=1 # note that array element position starts from 1 not, 0 |
| while json_is_a ${idx} string | while json_is_a ${idx} string | ||
| do | do | ||
| Line 136: | Line 138: | ||
| </ | </ | ||
| + | |||
| + | === Parse list of objects === | ||
| + | |||
| + | The example will download electricity hourly prices for Finland in JSON and parse it. | ||
| + | The prices JSON looks like | ||
| + | <code - prices.json> | ||
| + | { | ||
| + | " | ||
| + | { | ||
| + | " | ||
| + | " | ||
| + | }, | ||
| + | { | ||
| + | " | ||
| + | " | ||
| + | }, | ||
| + | ] | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | Script to parse it: | ||
| + | <code bash> | ||
| + | #!/bin/sh | ||
| + | set -e | ||
| + | . / | ||
| + | date=$(date -u +%Y-%m-%dT%H: | ||
| + | |||
| + | # download prices JSON via wget in quiet mode with output to stdout that will be saved to a variable PRICES_JSON | ||
| + | PRICES_JSON=$(wget -qO - " | ||
| + | exit_status=$? | ||
| + | # check exit code: if any error then exit | ||
| + | if [ $exit_status -ne 0 ]; then | ||
| + | >& | ||
| + | exit $exit_status | ||
| + | fi | ||
| + | |||
| + | json_load " | ||
| + | json_select " | ||
| + | idx=1 # note that array element position starts from 1 not, 0 | ||
| + | # iterate over data inside " | ||
| + | while json_is_a $idx object | ||
| + | do | ||
| + | json_select | ||
| + | # now parse {" | ||
| + | json_get_var price_date " | ||
| + | echo " | ||
| + | json_get_var price_value " | ||
| + | echo " | ||
| + | idx=$(( idx + 1 )) | ||
| + | json_select .. # go back to the upper level to the prices array | ||
| + | done | ||
| + | |||
| + | echo "Total parsed $idx" | ||
| + | </ | ||
| ===== json_for_each_item ===== | ===== json_for_each_item ===== | ||
| Line 403: | Line 459: | ||
| ==== See also ==== | ==== See also ==== | ||
| - | * [[https:// | + | |
| + | * [[https:// | ||
| + | * [[https:// | ||