2017-09-08 5 views
1

json配列からデータを取得して取得する必要がありますが、特定の配列インデックスを取得して値を出力する方法がわかりません。それについてのオンライン情報もないようです。Luaが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) 

出力:

admin 

別の解決法(JSONのフルデコードして、よりシンプル):あなたの助けのための

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

関連する問題