Helpful Command Line Utilties

DISCLAIMER: These work on Mac OS X 10.9 and Debian Linux. Your mileage may vary with other operating systems though it does look like the jq utility mentioned in this post has a Windows executable available.

If you are using cURL already for testing and wanting to parse the JSON response easily via the command-line, there are some simple utilities that can help out with that. You may want to check out 7 command-line tools for data science. In particular, jq is very handy.

An example command to grab variable data from your Core and view the results in a prettier format would be: curl -s “https://api.spark.io/v1/devices/DEVICE_ID/YOUR_VARIABLE?access_token=ACCESS_TOKEN” | jq ‘.’

And the output would look something like this:
{
  “cmd”: “VarReturn”,
  “name”: “YOUR_VARIABLE”,
  “allTypes”: {
    “string”: “\u0000\u0000\b_”,
    “uint32”: 2143,
    “number”: 2143,
    “double”: null,
    “raw”: “\u0000\u0000\b_”
  },
  “result”: “\u0000\u0000\b_”,
  “coreInfo”: {
    “last_app”: “foo”,
    “last_heard”: “2013-12-22T22:02:48.842Z”,
    “connected”: false,
    “deviceID”: “DEVICE_ID”
  }
}

We can then narrow that down to just the allTypes data using: jq ‘.allTypes’ instead of jq ‘.’. The full command would be: curl -s “https://api.spark.io/v1/devices/DEVICE_ID/YOUR_VARIABLE?access_token=ACCESS_TOKEN” | jq ‘.allTypes’.

The results would then look something like this:
{
  “string”: “\u0000\u0000\b_”,
  “uint32”: 2143,
  “number”: 2143,
  “double”: null,
  “raw”: “\u0000\u0000\b_”
}

What you really may want to do is be able to get that number without any extra formatting. Easy! Just add .number to your jq command and make it look like jq ‘.allTypes.number’. That full command should look like this: curl -s “https://api.spark.io/v1/devices/DEVICE_ID/YOUR_VARIABLE?access_token=ACCESS_TOKEN” | jq ‘.allTypes.number’.

The only output of that command will be the value in the number field: 2143. Now that is something you could use in simple shell and batch scripts! I would recommend also checking out some of the other utilities described in the article mentioned above.

I hope this helps someone out there make their life a little easier. Happy hacking!

2 Likes

@wgbartley Nice! this is really handy, I haven’t used jq before, but I’m looking forward to it, seems like a great tool for this kind of thing.

For other folks appreciating @wgbartley’s recommendation, I also wanted to mention that we’re working on getting the “result” JSON key to return the value you’d expect with the correct type. Will likely have a fix pushed sometime shortly after the holidays at which point (if I understand jq correctly), you’ll be able to just do ... | jq '.result'.

1 Like