EndPointCorp / end-point-blog

End Point Dev blog
https://www.endpointdev.com/blog/
17 stars 65 forks source link

Comments for Making sense of XML/JSON items in the shell #1578

Open jonjensen opened 4 years ago

jonjensen commented 4 years ago

Comments for https://www.endpointdev.com/blog/2019/12/making-sense-of-xml-json-in-shell/ By Muhammad Najmi bin Ahmad Zabidi

To enter a comment:

  1. Log in to GitHub
  2. Leave a comment on this issue.
candlerb commented 2 years ago

The sample code shows:

sumber=$(curl -s "https://api.exchangeratesapi.io/api/latest?base=$sourcemoney" | jq . | grep -i $target | awk -F ':|,' '{ print $2 }')

However, there is no need for grep and awk here: jq can extract the value from JSON directly and safely.

# quick and dirty way - will fail if $target contains spaces or special characters
sumber=$(curl -s "https://api.exchangeratesapi.io/api/latest?base=$sourcemoney" | jq ".rates.$target")

# slightly better
sumber=$(curl -s "https://api.exchangeratesapi.io/api/latest?base=$sourcemoney" | jq ".rates[\"$target\"]")

# completely safe and secure way
export target
sumber=$(curl -s "https://api.exchangeratesapi.io/api/latest?base=$sourcemoney" | jq '.rates[env.target]')
jonjensen commented 2 years ago

@candlerb Very nice improvement!

raden commented 2 years ago

@candlerb Thank you :+1: