简体   繁体   English

将字符串转换为lua中的映射

[英]Convert string to map in lua

I am quite new to lua. 我对lua很陌生。 I trying to convert a string of the form 我试图转换形式的字符串

{"result": "success", "data":{"shouldLoad":"true"}"}

into lua map. 进入lua地图。 So that I can access it like json. 这样我就可以像json一样访问它。 eg someMap[data][shouldLoad] => true

I dont have any json bindings in lua. 我在lua中没有任何json绑定。 I also tried loadstring to convert string of the form {"result" = "success", "data"={"shouldLoad"="true"}"} , which is not working. 我还尝试了loadstring来转换格式为{"result" = "success", "data"={"shouldLoad"="true"}"} ,它不起作用。

Following, is the code snippet, where I am calling getLocation hook, which in turn returns json stringified map. 接下来是代码片段,我在其中调用getLocation钩子,该钩子又返回json字符串化映射。 Now I want to access some keys from this response body and take some decisions accordingly. 现在,我想从此响应主体访问一些键,并据此做出一些决定。

access_by_lua "
    local res = ngx.location.capture('/getLocation')

    //res.body = {"result"= "success", "data" = {"shouldLoad" = "true"}}
    local resData = loadstring('return '..res.body)()

    local shoulLoad = resData['data']['shouldLoad']
" 

When I try to load shouldLoad value, nginx error log reports error saying trying to index nil value. 当我尝试加载shouldLoad值时,nginx错误日志会报告错误,指出尝试索引nil值。

How do I access key value with either of the string formats. 如何使用任何一种字符串格式访问键值。 Please help. 请帮忙。

The best answer is to consider a pre-existing JSON module, as suggested by Alexey Ten. 最好的答案是考虑Alexey Ten建议的预先存在的JSON模块。 Here's the list of JSON modules from Alexey. 这是Alexey 的JSON模块列表

I also wrote a short pure-Lua json module that you are free to use however you like. 我还编写了一个简短的pure-Lua json模块 ,您可以随意使用它。 It's public domain, so you can use it, modify it, sell it, and don't need to provide any credit for it. 它是公共领域,因此您可以使用,修改,出售它,而无需为此提供任何荣誉。 To use that module you would write code like this: 要使用该模块,您需要编写如下代码:

local json = require 'json'  -- At the top of your script.

local jsonStr = '{"result": "success", "data":{"shouldLoad":"true"}"}'
local myTable = json.parse(jsonStr)

-- Now you can access your table in the usual ways:
if myTable.result == 'success' then
  print('shouldLoad =', myTable.data.shouldLoad)
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM