Reputation: 6502
I am trying to extract a value from a json encoded string that returned from a sorted set in Redis.
127.0.0.1:6379> eval 'local r= redis.call("ZRANGEBYSCORE", "iprange:locations", 34625535, "+inf", "LIMIT", 0, 1); return type(r);' 0
"table"
127.0.0.1:6379> eval 'local r= redis.call("ZRANGEBYSCORE", "iprange:locations", 34625535, "+inf", "LIMIT", 0, 1); return r;' 0
1) "{\"countryCode\": \"IT\", \"countryName\": \"Italy\"}"
I just want to extract countryValue
from the result.
Tried return r.countryCode;
, return r["countryCode"];
but all of them returned (nil)
By the way, I alread handle this json encoded string in my app by decoding this json into data. Just trying to delegate this simple task to Redis Lua script engine.
Upvotes: 0
Views: 414
Reputation: 48902
Use the built-in JSON library:
eval 'local r = redis.call("ZRANGEBYSCORE", "iprange:locations", 34625535, "+inf", "LIMIT", 0, 1);
return cjson.decode(r[1])["countryCode"];'
Note that ZRANGEBYSCORE
returns an array of results, represented in Lua by a table
. Presumably you'll want to loop over the results and extract countryCode
for each.
Upvotes: 2