Lua script converts empty array to object
Asked Answered
D

3

5

Lua script converts empty array as an object. How to avoid conversion.

test.lua

local json_str = '{\"items\":[],\"properties\":{}}'
return cjson.encode(cjson.decode(json_str))

Output

redis-cli --eval test.lua

"{\"items\":{},\"properties\":{}}"

items are an array [] but the output is an object {}

Dubitable answered 25/2, 2020 at 16:7 Comment(2)
This was asked here: https://mcmap.net/q/1827979/-redis-lua-differetiating-empty-array-and-object/12918181Waddle
In the above question, I am not able to find relation between emptyArray() and toJsonStr() function . Can you help me to modify second approach Fix by code an above answer.Dubitable
W
3

The main difference between JSON object definition and lua table, that lua table has no type array.

Empty JSON array [] or object {} is converted to lua table {}, but empty lua table {} can be converted to array [] or object {}.

To my knowledge, cjson for redis has no solution for this problem at the moment, possible solution is mentioned in Redis Lua Differetiating empty array and object. (I can't argue if it works)

Waddle answered 25/2, 2020 at 20:47 Comment(0)
S
3

According to this great post you can set the following option to cjson:

cjson.encode_empty_table_as_object(false)

So cjson.encode({dogs = {}}) resolves to {"dogs": []}

Surmount answered 23/11, 2021 at 8:13 Comment(0)
I
0

This worked for me: setmetatable(table, cjson.array_mt)

Ileostomy answered 28/11, 2023 at 11:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.