1 개요[ | ]
- Lua json_encode()
- 간단히 구현. 단, nil(null)은 제대로 처리되지 않는다.
lua
Copy
function json_encode(val)
if type(val) == 'string' then return '"'..val..'"' end
if type(val) ~= 'table' then return tostring(val) end
local res = {}
if rawget(val, 1) ~= nil then
for i, v in ipairs(val) do table.insert(res, json_encode(v)) end
return "[" .. table.concat(res, ",") .. "]"
end
for k, v in pairs(val) do table.insert(res, json_encode(k) .. ":" .. json_encode(v)) end
return "{" .. table.concat(res, ",") .. "}"
end
print( json_encode({1,2,"3","hello",true,false}) ) -- [1,2,"3","hello",true,false]
print( json_encode({a=1, b={a=1, b=2, c=false}, c=42}) ) -- {"b":{"b":2,"c":false,"a":1},"c":42,"a":1}
print( json_encode({true, "a", 1, 2, {x=9, y="b", z={3.1,"x"}}}) ) -- [true,"a",1,2,{"z":[3.1,"x"],"x":9,"y":"b"}]
Loading
2 같이 보기[ | ]
편집자 Jmnote
로그인하시면 댓글을 쓸 수 있습니다.