Lua使用cURL从json数组中获取数据

我需要进行一次get请求,并从json数组中检索数据,但我不知道如何提取特定的数组索引并打印它的值。似乎也没有任何关于它的在线信息。

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()

这会返回

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

但我该如何只打印"name"的值?

点赞
用户6834680
用户6834680

你可以使用一些 JSON 库,例如 这个

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  -- 如果当前元素对应于 JSON [1] .name
      print(value)
   end
end

local JSON_string = [[

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

]]

json.traverse(JSON_string, callback)

输出:

admin

另一种解决方案(更简单,完全解码 JSON):

local json = require'json'

local JSON_string = [[

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

]]

print(json.decode(JSON_string)[1].name)
2017-09-08 15:24:04