Skip to content

Instantly share code, notes, and snippets.

@ninadsp
Last active August 26, 2022 15:06
Show Gist options
  • Save ninadsp/11075000 to your computer and use it in GitHub Desktop.
Save ninadsp/11075000 to your computer and use it in GitHub Desktop.
Use jq to conditionally pick up fields from a JSON
  • 1.json contains data retrieved from the Instagram API. data is an array of media matching the query posted to Instagram's REST API, in a JSON array.
  • Each media element contains metadata for a photo/video posted to Instagram
  • .data[] loops over each media object in the JSON file, letting us process each element
  • | works like a regular *nix pipe, taking the output of the previous operator and passing it on to the next one.
  • select() filters through objects depending on the rule passed to it.
  • .tags[] returns an array of tags for each media. contains() returns true if the current object passed to it contains the string passed as a parameter. .tags[] | contains("100happydays") iterates over all the tags associated with the media object and returns true if the current tag matches the string 100happydays.
  • .select( .tags[] | contains("100happydays") ) filters all media objects that contain the tag 100happydays
  • .images.standard_resolution.url now prints the value of the url inside the standard_resolution object contained in the images array, for each media that select returned

Thus, we only print URLs for Instagram media containing the "100happydays" hashtag.

Hattip to ghost's extremely detailed explanation here

jq '.data[] | select ( .tags[] | contains("100happydays") ) | .images.standard_resolution.url' 1.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment