Skip to content

Instantly share code, notes, and snippets.

@narate
Last active August 29, 2015 14:14
Show Gist options
  • Save narate/5712055078395429cd6f to your computer and use it in GitHub Desktop.
Save narate/5712055078395429cd6f to your computer and use it in GitHub Desktop.
Command line JSON parser.
#!/usr/bin/env luajit
-- author : Narate Ketram
-- github.com/narate
-- $ echo '{"name":"narate"}' | parse_json name
-- "narate"
local cjson = require 'cjson.safe'
local data = io.read('*all')
local json = cjson.decode(data)
if not json then
print('Invalid json')
return
end
local key = tonumber(arg[1]) or arg[1]
if not key then
print(data)
return
end
print(cjson.encode(json[key]) or 'not found')
@narate
Copy link
Author

narate commented Feb 4, 2015

Requirement

  • luajit 2.x+
  • cjson 2.1.x+ (with cjson.safe support)

Setup

  • Download parse_json
  • Make parse_json executable ( $ chmod +x parse_json )
  • Add parse_json to your $PATH

Example

$ curl -s httpbin.org/headers
{
  "headers": {
    "Accept": "*/*",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.37.1"
  }
}
$ curl -s httpbin.org/headers | parse_json headers
 {"Accept":"*\/*","User-Agent":"curl\/7.37.1","Host":"httpbin.org"}
$ curl -s httpbin.org/headers | parse_json headers | parse_json Host
"httpbin.org"

@iporsut
Copy link

iporsut commented Mar 11, 2015

ผมลง luajit และใช้ luarocks ลง lua-cjson แต่ว่ามันหา cjson ไม่เจอนะครับ ทำยังไงดี

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment