all: 5.2 compatibility
[luajson.git] / lua / json / encode / object.lua
blobe6b4bb2aa05998f0c3e9faebdd778e1df3bf30d1
1 --[[
2 Licensed according to the included 'LICENSE' document
3 Author: Thomas Harning Jr <harningt@gmail.com>
4 ]]
5 local pairs = pairs
6 local assert = assert
8 local type = type
9 local tostring = tostring
11 local table_concat = require("table").concat
12 local util_merge = require("json.util").merge
14 local is_52 = _VERSION == "Lua 5.2"
15 local _G = _G
17 if is_52 then
18 _ENV = nil
19 end
21 local defaultOptions = {
24 local default = nil
25 local strict = nil
27 --[[
28 Cleanup function to unmark a value as in the encoding process and return
29 trailing results
31 local function unmarkAfterEncode(tab, state, ...)
32 state.already_encoded[tab] = nil
33 return ...
34 end
35 --[[
36 Encode a table as a JSON Object ( keys = strings, values = anything else )
38 local function encodeTable(tab, options, state)
39 -- Make sure this value hasn't been encoded yet
40 state.check_unique(tab)
41 local encode = state.encode
42 local compositeEncoder = state.outputEncoder.composite
43 local valueEncoder = [[
44 local first = true
45 for k, v in pairs(composite) do
46 local ti = type(k)
47 assert(ti == 'string' or ti == 'number' or ti == 'boolean', "Invalid object index type: " .. ti)
48 local name = encode(tostring(k), state, true)
49 if first then
50 first = false
51 else
52 name = ',' .. name
53 end
54 PUTVALUE(name .. ':')
55 local val = encode(v, state)
56 val = val or ''
57 if val then
58 PUTVALUE(val)
59 end
60 end
62 return unmarkAfterEncode(tab, state, compositeEncoder(valueEncoder, '{', '}', nil, tab, encode, state))
63 end
65 local function getEncoder(options)
66 options = options and util_merge({}, defaultOptions, options) or defaultOptions
67 return {
68 table = function(tab, state)
69 return encodeTable(tab, options, state)
70 end
72 end
74 local object = {
75 default = default,
76 strict = strict,
77 getEncoder = getEncoder
80 if not is_52 then
81 _G.json = _G.json or {}
82 _G.json.encode = _G.json.encode or {}
83 _G.json.encode.object = object
84 end
86 return object