Redis 中的 Lua 从 JSON。

我在Redis中有一些JSON字符串的列表,看起来像这样:

[
   { "ID": 25, "DomainID": 23455, "Name": "Stuff", "Value": 23 },
   { "ID": 35, "DomainID": 23455, "Name": "Stuff", "Value": 10 }
]

键将类似于“Event:23455”。

使用Lua脚本和ServiceStack.Redis,我将如何提取包含仅在值小于20时的值的匿名对象?

因此,我想要返回的内容看起来像这样:

[{ "ID": 35, "Value": 10}]

谢谢。

更新03/31/2013:

尝试建议的内容后,我现在有一个新问题。 Lua脚本语法错误。

我遇到了一个关于“附近的= cjson”的Lua语法错误。这是我正在向Redis提供的Lua脚本字符串(使用C#):

string luaScript = "local tDecoded = cjson.decode(redis.call('GET', KEYS[1]));"
+ "local tFinal = {};"
+ "for iIndex, tValue in ipairs(tDecoded) do"
+ "     if tonumber( tValue.Value ) < 20 then"
+ "        table.insert(tFinal, { ID = tValue.ID, Value = tValue.Value});"
+ "     end"
+ "end"
+ "return cjson.encode(tFinal);";

有没有Lua或Redis Lua专家可以看到可能存在的问题?即Lua语法是否正确?

更新04/02/2013

通过向每行添加\n换行符来解决解析错误,就像这样。

string luaScript = "local tDecoded = redis.call('GET', KEYS[1]);\n"
+ "local tFinal = {};\n"
+ "for iIndex, tValue in ipairs(tDecoded) do\n"
+ "     if tonumber( tValue.Value ) < 20 then\n"
+ "        table.insert(tFinal, { ID = tValue.ID, Value = tValue.Value});\n"
+ "     else\n"
+ "         table.insert(tFinal, { ID = 999, Value = 0});\n"
+ "     end\n"
+ "end\n"
+ "return cjson.encode(tFinal);";

不幸的是,这可以正常工作,但由某种原因仅在ServiceStack RedisClient中返回“{}”或空列表。因此,我还没有完成。

点赞
用户1190388
用户1190388

你可以使用GitHub上可用的LuaJSON,或者你也可以尝试这个JSON转Lua表解析器来完成任务。使用方法将类似于这样(对于GitHub链接):

local json = require("json")  -- 或者 JSON.lua
local tDecoded = json.decode(sJSON)  -- sJSON是原始的JSON字符串

local tFinal = {}

for iIndex, tValue in ipairs(tDecoded) do
    if tonumber(tValue.Value) < 20 then
        table.insert(tFinal, { ID = tValue.ID, Value = tValue.Value })
    end
end

print(json.encode(tFinal))
2013-03-31 04:24:24