在Corona Lua中的JSON中发生错误。

嗨,我找到了一篇关于如何在Lua中使用post json的教程。

以下是代码:

http = require("socket.http")
crypto = require("crypto")
ltn12 = require("ltn12")
url = require("socket.url")
local json = require("json")

local commands_json =
{

                ["message"] = "Hello",

}
print (commands_json)
local json = {}
json.api_key = "6_192116334"
json.ver = 1
json.commands_json = json.encode(commands_json)
json.commands_hash = crypto.digest(crypto.md5, json.commands_json .. 'hkjhkjhkjh')

local post = "api=" .. url.escape(Json.Encode(json))
local response = {}

local r, c, h = http.request {
    url = "http://127.0.0.1/?page=api",
    method = "POST",
    headers = {
        ["content-length"] = #post,
        ["Content-Type"] =  "application/x-www-form-urlencoded"
    },
    source = ltn12.source.string(post),
    sink = ltn12.sink.table(response)
}

local path = system.pathForFile("r.txt", system.DocumentsDirectory)
local file = io.open (path, "w")
file:write (Json.Encode(json) .. "\n")
file:write (post .. "\n")
file:write (response[1] .. "\n")
io.close (file)

json = Json.Decode(table.concat(response,''))
native.showAlert("hey", json.commands[1].tot_nbr_rows)

现在我得到了以下错误:

Windows simulator build date: Dec 9 2011 @ 14:01:29

Copyright (C) 2009-2011 Ansc a, Inc.
Version: 2.0.0
Build: 2011.704
table: 0346D6D0
Runtime error
...nistrator\my documents\corona projects\json\main.lua:17: attempt to c
all field 'encode' (a nil value)
stack traceback:
        [C]: in function 'encode'
        ...nistrator\my documents\corona projects\json\main.lua:17: in main chun
k
Runtime error: ...nistrator\my documents\corona projects\json\main.lua:17: attem
pt to call field 'encode' (a nil value)
stack traceback:
        [C]: in function 'encode'
        ...nistrator\my documents\corona projects\json\main.lua:17: in main chun
k

我不知道为什么会出现“encode”的错误。

有人能帮助我解决这个问题吗?

提前感谢...

原文链接 https://stackoverflow.com/questions/10429040

点赞
stackoverflow用户596285
stackoverflow用户596285

这包括从外部提供的 Json 代码,可能带有编码函数:

local json = require("json")

这将丢弃您旧的 json 变量,并将其替换为空表:

local json = {}

并且这会尝试调用 json.encode,因为您在上面将 json 重新定义为空表,所以它现在是未定义的:

json.commands_json = json.encode(commands_json)

解决方案是选择一个不同的变量名。

2012-05-03 12:30:21