Comparison

util/json.lua @ 4474:b08a46cf06e6

util.json: Added function encode_ordered(object).
author Waqas Hussain <waqas20@gmail.com>
date Wed, 18 Jan 2012 08:54:26 +0500
parent 4404:5356664ef9d4
child 5395:ec33d72a08b6
comparison
equal deleted inserted replaced
4473:7e2cf20aef74 4474:b08a46cf06e6
1 1
2 local type = type; 2 local type = type;
3 local t_insert, t_concat, t_remove = table.insert, table.concat, table.remove; 3 local t_insert, t_concat, t_remove, t_sort = table.insert, table.concat, table.remove, table.sort;
4 local s_char = string.char; 4 local s_char = string.char;
5 local tostring, tonumber = tostring, tonumber; 5 local tostring, tonumber = tostring, tonumber;
6 local pairs, ipairs = pairs, ipairs; 6 local pairs, ipairs = pairs, ipairs;
7 local next = next; 7 local next = next;
8 local error = error; 8 local error = error;
77 end 77 end
78 end 78 end
79 if next(__hash) ~= nil or next(hash) ~= nil or next(__array) == nil then 79 if next(__hash) ~= nil or next(hash) ~= nil or next(__array) == nil then
80 t_insert(buffer, "{"); 80 t_insert(buffer, "{");
81 local mark = #buffer; 81 local mark = #buffer;
82 for k,v in pairs(hash) do 82 if buffer.ordered then
83 stringsave(k, buffer); 83 local keys = {};
84 t_insert(buffer, ":"); 84 for k in pairs(hash) do
85 simplesave(v, buffer); 85 t_insert(keys, k);
86 t_insert(buffer, ","); 86 end
87 t_sort(keys);
88 for _,k in ipairs(keys) do
89 stringsave(k, buffer);
90 t_insert(buffer, ":");
91 simplesave(hash[k], buffer);
92 t_insert(buffer, ",");
93 end
94 else
95 for k,v in pairs(hash) do
96 stringsave(k, buffer);
97 t_insert(buffer, ":");
98 simplesave(v, buffer);
99 t_insert(buffer, ",");
100 end
87 end 101 end
88 if next(__hash) ~= nil then 102 if next(__hash) ~= nil then
89 t_insert(buffer, "\"__hash\":["); 103 t_insert(buffer, "\"__hash\":[");
90 for k,v in pairs(__hash) do 104 for k,v in pairs(__hash) do
91 simplesave(k, buffer); 105 simplesave(k, buffer);
124 end 138 end
125 end 139 end
126 140
127 function json.encode(obj) 141 function json.encode(obj)
128 local t = {}; 142 local t = {};
143 simplesave(obj, t);
144 return t_concat(t);
145 end
146 function json.encode_ordered(obj)
147 local t = { ordered = true };
129 simplesave(obj, t); 148 simplesave(obj, t);
130 return t_concat(t); 149 return t_concat(t);
131 end 150 end
132 151
133 ----------------------------------- 152 -----------------------------------