Using jq to manipulate JSON in command line
Sometimes during the testing of REST API with curl in the command line, we need to process JSON from the response to present it in readable format or check a specific key or value. I used jq utility for that purpose and didn’t pay too much attention to how powerful it can be:
curl https://mysuperapi.com/superendpoint | jq
Recently, I found this article showed many cool examples of using jq. For example, to get a list of all sensors from this JSON:
[ { "name": "Station1", "location": "Centerville", "sensors": ["temperature", "humidity"] }, { "name": "Station5", "location": "Anytown", "sensors": ["temperature", "humidity", "rainfall", "wind_speed"] } ]
the following command can be used:
curl https://mysuperapi.com/superendpoint | jq -r '.[] .sensors[]'
The result will be like this:
temperature humidity temperature humidity rainfall wind_speed