Fun with CLI, JSON and .jq

We are terminal junkies at CloudSpokes so we were really excited when the CLI was announced. One of our favorite command line tools is .jq, a lightweight and flexible command-line JSON processor. My buddy and terminal Yoda, Kyle Bowerman, turned me on to this utility. jq is like sed for JSON data – you can use it to slice and filter and map and transform structured data with the same ease as sed, awk, grep.

So how does this work with Salesforce you ask? You can make virtually any call that returns JSON (let's say a REST API query), search through the JSON, pipe the results into a shell script and then run that with the CLI.

The first thing you need to do is install .jq. Not terribly hard as they have binaries for most systems. Then you'll need to get a session token for the REST API call. You'll need to pass this session Id in the header with each REST call. Log into the Workbench for your org and go to Info -> Session Information. You'll see your session Id under the Connection folder.

So the simplest use case is to query for 3 accounts and run them through .jq to see what we get:

curl,+id+from+account+order+by+id+limit+3 -H 'Authorization: Bearer [YOUR-SESSION-ID]' | jq '.'


So let's say now that you want to get just the Names for all of these records. These are stored in the 'records' property so we are gonna tell .jq to iterate over the records array and just output the Name property:

curl,+id+from+account+order+by+id+limit+3 -H 'Authorization: Bearer [YOUR-SESSION-ID]' | jq '.records[].Name'


Now here's where the fun stuff begins. Let's use .jq to create a shell script to run with the CLI to update some records:

curl,+id+from+account+order+by+id+limit+3 -H 'Authorization: Bearer [YOUR-SESSION-ID]' | jq '"force record update Account (.records[].Id) State:NY"'


You can easily send the contents generated by .jq to a shell script that you can execute against your org by appending '>':

curl,+id+from+account+order+by+id+limit+3 -H 'Authorization: Bearer [YOUR-SESSION-ID]' | jq '"force record update Account (.records[].Id) State:NY"' >

There are a ton of things you can do with .jq so make sure you check out the manual. Happy scripting! Enjoy!

Loading comments...