在lua中解码JSON的问题

问题描述

我有以下代码

PerformHttpRequest('http://ossie.dk/API/verify.json',function(err,text,headers)
    local r=json.decode(text)
    for s,t in pairs(r.servers)do
         print(t)
    end
end,"GET","",{})
               

我的问题是,当解码来自verify.json的内容时,我一直收到以下错误错误的参数#1到'strfind'(期望的字符串,为nil)或试图做键的值是不是桌子。我真的很迷失了这一点,花了很多时间在这件事上。我认为整个问题是如何设置JSON。它必须是一个字符串,但也要是一个表,以后可以用作键,值对,以便从中获取所有信息。我希望这能带来某种意义。

脚本错误来自此处:

local function scanwhite (str,pos)
  while true do
    pos = strfind (str,"%s",pos)
    if not pos then return nil end
    local sub2 = strsub (str,pos,pos + 1)
    if sub2 == "\239\187" and strsub (str,pos + 2,pos + 2) == "\191" then
      -- UTF-8 Byte Order Mark
      pos = pos + 3
    elseif sub2 == "//" then
      pos = strfind (str,"[\n\r]",pos + 2)
      if not pos then return nil end
    elseif sub2 == "/*" then
      pos = strfind (str,"*/",pos + 2)
      if not pos then return nil end
      pos = pos + 2
    else
      return pos
    end
  end
end

我当前的JSON如下所示:

{   
    { "servers": 
        "ip": 
        [
            "144","155","166"
        ]
    }
}

顺便说一句,我尝试更改

r.servers

使用

r.ip

然后给出以下内容:无效的向量字段:ip

如果我愿意

for k,v in pairs(r) do

这会给我这个错误

Table expected,got string

我正在使用FiveM的JSON库。

如果您有任何疑问或不明白我的意思,请随时在评论中提问。

解决方法

您键入了str:find()和str:sub()命令。

local function scanwhite( str,pos )
  while true do
    pos = str :find( "%S",pos )
    if not pos then return nil end
    local sub1 = str :sub( pos,pos +1 )
    local sub2 = str :sub( pos +2,pos +2 )
    if sub1 == "\239\187" and sub2 == "\191" then
      -- UTF-8 Byte Order Mark
      pos = pos +3
    elseif sub1 == "//" then
      pos = str :find( "[\n\r]",pos +2 )
      if not pos then return nil end
    elseif sub1 == "/*" then
      pos = str :find( "*/",pos +2 )
      if not pos then return nil end
      pos = pos +2
    else
      return pos
    end
  end
end
,

第一个 JSON 有点问题。您使用一个对象,但没有向 JSON 声明您将使用它。试试这个

{   
    { "servers":
        { 
            "ip": [
                "144","155","166"
            ]
        }
    }
}