From 7a9c25ee69f38974e99322971eace37ba1753074 Mon Sep 17 00:00:00 2001 From: Thibault Charbonnier Date: Sun, 28 Feb 2016 20:03:12 -0800 Subject: feat: cjson.as_array metamethod to enforce empty array encoding A proposed improved patch of openresty/lua-cjson#1 (a patch commonly proposed to lua-cjson and its forks), taking into considerations comments from the original PR. - use a lightuserdata key to store the metatable in the Lua Registry (more efficient and avoiding conflicts) - provide a lightuserdata resulting in empty arrays as well - tests cases moved to t/agentzh.t, where cases for 'encode_empty_table_as_object' are already written. It seems like a better place for tests specific to the OpenResty fork's additions. - a more complex test case --- tests/agentzh.t | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 74 insertions(+), 2 deletions(-) (limited to 'tests') diff --git a/tests/agentzh.t b/tests/agentzh.t index 0b546ff..e76f910 100644 --- a/tests/agentzh.t +++ b/tests/agentzh.t @@ -41,7 +41,79 @@ print(cjson.encode({dogs = {}})) -=== TEST 4: & in JSON +=== TEST 4: empty_array userdata +--- lua +local cjson = require "cjson" +print(cjson.encode({arr = cjson.empty_array})) +--- out +{"arr":[]} + + + +=== TEST 5: empty_array_mt +--- lua +local cjson = require "cjson" +local empty_arr = setmetatable({}, cjson.empty_array_mt) +print(cjson.encode({arr = empty_arr})) +--- out +{"arr":[]} + + + +=== TEST 6: empty_array_mt and empty tables as objects (explicit) +--- lua +local cjson = require "cjson" +local empty_arr = setmetatable({}, cjson.empty_array_mt) +print(cjson.encode({obj = {}, arr = empty_arr})) +--- out +{"arr":[],"obj":{}} + + + +=== TEST 7: empty_array_mt and empty tables as objects (explicit) +--- lua +local cjson = require "cjson" +cjson.encode_empty_table_as_object(true) +local empty_arr = setmetatable({}, cjson.empty_array_mt) +local data = { + arr = empty_arr, + foo = { + obj = {}, + foobar = { + arr = cjson.empty_array, + obj = {} + } + } +} +print(cjson.encode(data)) +--- out +{"foo":{"foobar":{"obj":{},"arr":[]},"obj":{}},"arr":[]} + + + +=== TEST 8: empty_array_mt on non-empty tables +--- lua +local cjson = require "cjson" +cjson.encode_empty_table_as_object(true) +local array = {"hello", "world", "lua"} +setmetatable(array, cjson.empty_array_mt) +local data = { + arr = array, + foo = { + obj = {}, + foobar = { + arr = cjson.empty_array, + obj = {} + } + } +} +print(cjson.encode(data)) +--- out +{"foo":{"foobar":{"obj":{},"arr":[]},"obj":{}},"arr":["hello","world","lua"]} + + + +=== TEST 9: & in JSON --- lua local cjson = require "cjson" local a="[\"a=1&b=2\"]" @@ -52,7 +124,7 @@ print(cjson.encode(b)) -=== TEST 5: default and max precision +=== TEST 10: default and max precision --- lua local math = require "math" local cjson = require "cjson" -- cgit v1.2.3-55-g6feb