local cjson = require "cjson"
-- Module instantiation
-- 实例化模块
local cjson2 = cjson.new()
local cjson_safe = require "cjson.safe"
-- Translate Lua value to/from JSON
text = cjson.encode(value)
value = cjson.decode(text)
-- Get and/or set Lua CJSON configuration
setting = cjson.decode_invalid_numbers([setting])
setting = cjson.encode_invalid_numbers([setting])
keep = cjson.encode_keep_buffer([keep])
depth = cjson.encode_max_depth([depth])
depth = cjson.decode_max_depth([depth])
convert, ratio, safe = cjson.encode_sparse_array([convert[, ratio[, safe]]])
local cjson = require "cjson"
local cjson2 = cjson.new()
local cjson_safe = require "cjson.safe"
cjson
解码/编码的时候遇到非法数据会抛出错误cjson_safe
和cjson
一样,但是遇到非法数据时,不会抛错误,而是返回nil
和error
.cjson.new()
会创建一个实例,拥有自己独立的编码缓冲区和默认设置.value = cjson.decode(json_text)
json_text = '[ true, { "foo": "bar" } ]'
value = cjson.decode(json_text)
-- Returns: { true, { foo = "bar" } }
setting = cjson.decode_invalid_numbers([setting])
-- "setting" must be a boolean. Default: true.
true
: 会解析不可用的数字,默认设置false
: 当遇到不可用的数字会抛错误这个方法调用后会返回当前的设置值.
local in = cjson.decode_invalid_numbers(false)
--in is false
depth = cjson.decode_max_depth([depth])
-- "depth" must be a positive integer. Default: 1000.
json_text = cjson.encode(value)
value = { true, { foo = "bar" } }
json_text = cjson.encode(value)
-- Returns: '[true,{"foo":"bar"}]'
cjson.encode({ [3] = "data" })
-- Returns: '[null,null,"data"]'
cjson.encode_sparse_array(true)
cjson.encode({ [1000] = "excessively sparse" })
-- Returns: '{"1000":"excessively sparse"}'
null
解析json字符串的null值,会被解析为cjson.null.判断时
if value == cjson.null then ... end
,
lua_cjson
模块中可用方法和变量cjson.encode_empty_table_as_object(true|false|"on"|"off")
true
,空的lua 表会被编码为空的json对象{}
,如果设为false
,那么会被编码为json数组[]
cjson.empty_array
lightuserdata
,类似cjson.null
,这个值将会被编码为空的json数组[]
local cjson = require "cjson"
local json = cjson.encode({
foo = "bar",
some_object = {},
some_array = cjson.empty_array
})
将会生成json串:
{
"foo": "bar",
"some_object": {},
"some_array": []
}
setmetatable({}, cjson.array_mt)
local t = { "hello", "world" }
setmetatable(t, cjson.array_mt)
cjson.encode(t) -- ["hello","world"]
生成:
local t = {}
t[1] = "one"
t[2] = "two"
t[4] = "three"
t.foo = "bar"
setmetatable(t, cjson.array_mt)
cjson.encode(t) -- ["one","two",null,"three"]
setmetatable({}, cjson.empty_array_mt)
local function serialize(arr)
if #arr < 1 then
arr = cjson.empty_array
end
return cjson.encode({some_array = arr})
end
和上面相同:
local function serialize(arr)
setmetatable(arr, cjson.empty_array_mt)
return cjson.encode({some_array = arr})
end
最终结果都是:
{
"some_array": []
}
encode_number_precision
1-14
位,这里可以为1-16
位.