如何在 Lua 中简单地打印从 JSON 数据获取的数据?(为此,使用现有的 PHP 代码在 Lua 中编写)

Lua 中,我想要在设备的显示屏上打印 JSON API 数据(例如数据是http://biocache.ala.org.au/ws/occurrences/search?q=Banksia%20Serrata)。我相信我应该使用以下代码片段,但不确定如何正确使用。有人可以帮我快速吗?

local json = require( "json" )
network.request(url,"POST",listener,postData)

如果您知道 PHP,理解我的问题可能更容易。我有以下简单的 PHP 代码来通过 API 获取数据并打印它。我想在Lua中做同样的事情。

<?php
$handle = fopen("http://biocache.ala.org.au/ws/occurrences/search?q=Banksia%20Serrata", "r");
$contents = stream_get_contents($handle);
fclose($handle);
$jsoncont = json_decode($contents);
//print_r($jsoncont);
print "<h2>Results"</h2>";
foreach($jsoncont->occurrences as $occ) {
    print $occ->uuid."<br />";
}
?>

非常感谢!

PS 如果有很大的区别,非常感谢您能为我展示 POST 和 GET 的示例。

点赞
用户7665853
用户7665853

这对于像我这样的初学者来说并不容易,但我还是设法自己解决了问题!如果有人想知道并想使用,这是我谦卑的代码。无论如何,感谢 @Piglet!

如果有人能改进/简化它等等,也将不胜感激。

local json = require( "json" )
local function networkListener( event )
    local res = json.prettify( event.response )
    local decoded = json.decode( res )
    if ( event.isError ) then
        print( "--网络错误--", ( res ) )
    else
        print( "响应:" .. ( res ) )
        local item1 = decoded.pageSize
        local item2 = decoded.totalRecords
        print(item1)
        print(item2)

        local myText = display.newText(item1, 30, 10, native.systemFont, 16 )
        myText:setFillColor( 1, 1, 1 )
        local myText = display.newText(item2, 30, 40, native.systemFont, 16 )
        myText:setFillColor( 1, 1, 1 )
    end
end

local headers = {}
headers["Content-Type"] = "application/json"
local body = ""
local params = {}
params.headers = headers

params.body = body
network.request("http://biocache.ala.org.au/ws/occurrences/search?q=Banksia%20Serrata", "GET", networkListener, params)
2017-07-31 14:50:42