2017-09-08 2 views
1

json 배열에서 데이터를 가져오고 검색해야하지만 특정 배열 인덱스를 가져와 값을 인쇄하는 방법을 모르겠습니다. 그것에 관한 정보도 온라인에없는 것 같습니다.루아가 cURL을 사용하여 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의 값을 인쇄하는 방법을 만들 수 있습니까?

답변

1

일부 JSON 라이브러리 (예 : 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) 

출력 : (JSON의 전체 디코딩 더 간단)

admin 

또 다른 솔루션 : 당신의 도움에 대한

local json = require'json' 

local JSON_string = [[ 

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

]] 

print(json.decode(JSON_string)[1].name) 
+0

감사합니다. 내가 얻지 못하는 것은'c : perform()'이 콘솔에 모든 것을 출력하지만 변수에 컬을 저장하는 방법이다. 그러나 그 데이터를 저장할 옵션이없는 것 같다. 변수? –

+0

@ P.Nick - 아마도'c : setopt_writefunction (...)'이 도움이 될 수 있습니다. –

+1

쉬운 방법't = {} c : setopt_writefunction (table.insert, t)'그리고 수행 한 후에'str = table.concat (t)' – moteus

관련 문제