Reputation: 57
I want to make automatic script to parse JSON for some value and echo
-ing it to somewhere (in this case of test, terminal). Here is my complicated code:
for ((i = 0 ; i < 34 ; i++)); do
echo " \
$(curl -s https://data.covid19.go.id/public/api/prov.json | jq -r ".list_data[$i] .key"): \ # ex. Output: DKI Jakarta
$(curl -s https://data.covid19.go.id/public/api/prov.json | jq -r ".list_data[$i] .jumlah_kasus")"; # ex. Output: 580584
done
With this loop I got 34 lines:
DKI JAKARTA: 580584
JAWA BARAT: 402548
JAWA TENGAH: 265345
JAWA TIMUR: 178799
KALIMANTAN TIMUR: 79876
RIAU: 72361
SULAWESI SELATAN: 65330
DAERAH ISTIMEWA YOGYAKARTA: 65265
BANTEN: 59091
SUMATERA BARAT: 53125
BALI: 51499
SUMATERA UTARA: 36854
KALIMANTAN SELATAN: 36645
SUMATERA SELATAN: 29725
KEPULAUAN RIAU: 27854
KALIMANTAN TENGAH: 26719
LAMPUNG: 22731
KEPULAUAN BANGKA BELITUNG: 21976
PAPUA: 21150
NUSA TENGGARA TIMUR: 19977
ACEH: 19577
SULAWESI UTARA: 16633
KALIMANTAN BARAT: 15585
SULAWESI TENGAH: 13977
KALIMANTAN UTARA: 13466
JAMBI: 13332
NUSA TENGGARA BARAT: 13197
SULAWESI TENGGARA: 11948
PAPUA BARAT: 11682
BENGKULU: 10778
MALUKU: 9067
SULAWESI BARAT: 6043
GORONTALO: 5913
MALUKU UTARA: 5828
My question is: How can I sort the lines alphabetically with keeping province name and value synced?
E.g. like this:
ACEH: 19577
BALI: 51499
# etc...
Any answer will be appreciated, thank you. Let me know if there are something unclear so I can explain it.
Upvotes: 1
Views: 602
Reputation: 26727
Is this what you expected :
curl -s https://data.covid19.go.id/public/api/prov.json |\
jq -r '.list_data|sort_by(.key)[]|"\(.key): \(.jumlah_kasus)"'
Upvotes: 3
Reputation: 141613
Output stuff as one line with unique separator, sort, then replace that separtor with a newline.
for ...; do
echo "$(one)!$(two)"
done | sort | tr '!' '\n'
Upvotes: 1