参考: - https://redis-py.readthedocs.io/en/stable/lua_scripting.html - https://onecompiler.com/questions/3x6yguydg/how-to-encode-decode-json-objects-in-redis-lua-script
1. lua 解析 JSON
import redis
def parse_json():
r = redis.Redis()
lua = """
local value = redis.call('GET', KEYS[1])
local json = cjson.decode(tostring(value))
-- work with json
json.foo = 1
json.date = redis.call('TIME') --os.data("%Y-%m-%d %H:%M:%S") # 获取当前时间
local output = cjson.encode(json);
return output
"""
multiply = r.register_script(lua) # 注册 lua 代码,如果 lua 代码有语法错误,会注册失败
r.set('foo', '{}')
v = multiply(keys=['foo'], args=[]) # 调用 lua 代码
print(v)
2. lua 遍历 JSON
来源:https://juejin.cn/s/lua%20%E9%81%8D%E5%8E%86json
pairs
遍历键、值
for key, value in pairs(json) do
print(key, value)
end
ipairs
遍历索引、值
for index, value in ipairs(json) do
print(index, value)
end