2

I need to make a get request and retrieve data from a json array, but I don't know how to fetch a specific array index and print its value. There doesn't seem to be any information online about it either.

local curl = require("lcurl")

c = curl.easy{
    url = 'http://example.com/api/?key=1234',
    httpheader = {
      "Content-Type: application/json";
    };
    writefunction = io.stderr
  }
  c:perform()
c:close()

This returns

[
    {
        "id": "1",
        "name": "admin"
    }
]

But how can I make it print only the value of name?

1
  • Do you found a solution for your task? Commented Dec 18, 2018 at 9:25

1 Answer 1

1

You can use some JSON library, for example, this one.

local json = require'json'

local function callback(path, json_type, value, pos, pos_last)
   local elem_path = table.concat(path, '/')  -- element's path
   --print(elem_path, json_type, value, pos, pos_last)
   if elem_path == "1/name" then  -- if current element corresponds to JSON[1].name
      print(value)
   end
end

local JSON_string = [[

[
    {
        "id": "1",
        "name": "admin"
    }
]

]]

json.traverse(JSON_string, callback)

Output:

admin

Another solution (more simple, with full decoding of JSON):

local json = require'json'

local JSON_string = [[

[
    {
        "id": "1",
        "name": "admin"
    }
]

]]

print(json.decode(JSON_string)[1].name)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your help. What I don't get though is how I'd store the data from curl in a variable, as in c:perform() prints everything to the console but there doesn't seem to be an option to store that data into a variable?
@P.Nick - probably, c:setopt_writefunction(...) may help.
Easy way t={} c:setopt_writefunction(table.insert, t) And after perform do str = table.concat(t)
Please answer specifically to what OP requested (which is how to get from URL). I don't see any related URL in the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.