Month: October 2006

  • Web Services with JSON and Lua

    I’m still not sure why but today I wrote a web services client for the Yahoo! Traffic API using JSON and Lua.

    According to Wikipedia, Lua is a lightweight scripting language commonly embedded for use as an in-game scripting language. While it is most commonly used in gaming, I think it’s a simple but very powerful little scripting language.

    While exploring Lua a bit I stumbled upon the socket library and decided to couple that with a JSON parser. The short and sweet program checks and prints out traffic information for Kansas City, Missouri in about 20 decently commented lines. Here is some example output from the program.

    As with many short and sweet scripting language programs, this one relies on a few external libraries: Luasocket and JSON4Lua. The socket library uses Lua’s C bindings to work its magic but JSON4Lua (and many other extensions) are written in pure Lua. I’ve always been a sucker for a good library written in pure Python, and as such I love pure Lua extensions too.

    The JSON parser and HTTP library were particularly neat to work with, as was wrapping my head around Lua tables. Here’s the bit that parses the JSON response in to a Lua table:

    results = JSON.decode(r)[”ResultSet”][”Result”]

    Lua tables are neat in that you can access them in dict or attribute style so the above code can be rewritten as such:

    results = JSON.decode(r).ResultSet.Result

    If you’d like to read up on Lua a bit more I would suggest checking out the following sites: