0

Basically I've been using this code to read json file from web API and it's pretty easy using bash with jq package.

 #!/bin.bash
 ip_country=$(curl -s "https://api.ipgeolocationapi.com/geolocate/123.123.123.123}" | jq --raw-output '.name')
 if [ -z "$ip_country" ]; then
      ip_country="Unknown"
 fi
 echo "${ip_country}"

But, in lua, I have done some research and seems like lunajson is the best package to handle a json file (IMO). I know how to read a simple json file using lunajson but I found no example how to use this to read json file from a website like the bash example. Is there a special package that I need to import in order to read the json file from website (like the bash example above)?

Kalib Zen
  • 655
  • 1
  • 5
  • 16

1 Answers1

1

if you can install additional Lua packages (e.g. via Luarocks), then you can use the following pure-Lua solution (Tested with Lua 5.1.5 on Ubuntu):

-- read remote file from website
http = require("socket.http")
local body, code = socket.http.request("http://website/with/json/file.json")
if not body then error(code) end
local file = assert(io.open('file.json', 'w'))
file:write(body)
file:close()

-- read local file 
local open = io.open
local file = open("file.json", "rb")
if not file then return nil end
local jsonString = file:read "*a"
file:close()

-- parse json with lunajson
local json = require 'lunajson'
local t = lunajson.decode(jsonString)
print(t)

Note that you need to install socket.http and lunajson with:

luarocks install luasocket --local
luarocks install lunajson --local

And eventually you want to adjust your LUA_PATH by means of using luarocks path --bin respectively with eval $(luarocks path --bin) the LUA_PATH will be exported automatically.

stephanmg
  • 746
  • 6
  • 17