Making JSON more readable in the Terminal with Curl extension jq

jq banner

Advertisement:




When developing apps and games you may need to read JSON files quickly in the Terminal, this can be a pain.

JSON is a right pain to read in the Mac terminal but Cloudant have some great tips for viewing JSON here.

First of all here is a random JSON file displayed in the mac terminal using curl.

Terminal Command:

1
curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5'

json default

What a mess.

Solution

Install the ./jq lightweight command line JSON processor from http://stedolan.github.io/jq/

Install (type this in the terminal and install)

1
2
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install jq

fyi: Homebrew is a packaged installer (read more http://brew.sh/) and check out http://braumeister.org/ to see what other packages you can install.

Conclusion

Now lets try the curl command again with ” ! jq .” added to the end of the curl request.

Terminal Command:

1
curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jq .

color coded json in terminal

If you just want a web based tool try the Postman extension for Google Chrome.

Advertisement:




Simple lua function to catch a nil when checking json values

Simple lua function to catch a nil when checking json values

Advertisement:




function IsInString(theString, theText)
    print("IsInString (theString: '" .. theString .. "', theText: '" .. theText .. "').");
    if (tonumber(string.find(theString, theText)) == nil) then
        print(" String Not Found.");
        return false;
    else
        -- check the pos if the string to confirm (not nil is not enough)
        if (tonumber(string.find(theString, theText)) > 1) then
            print(" String Found.");
            return true;
        else
            print(" String Not Found.");
            return false;
        end
    end
end

I was doing this when processing json data but kept getting nil in the second elseif (nil was not being caught higher up.

if (event.response == nil) then
            --code
        elseif (event.response == "") then
            -- code
 
        elseif (tonumber(string.find(event.response, "ok")) > 1) then
            if (string.find(event.response, "true") > 1) then
                -- code
 
            end
            ...

Advertisement: