2016-01-08 23:39:50 +01:00
# CJSON Module
2016-03-05 10:47:01 +01:00
| Since | Origin / Contributor | Maintainer | Source |
| :----- | :-------------------- | :---------- | :------ |
2019-01-13 17:30:23 +01:00
| 2015-03-16 | [Mark Pulford ](http://kyne.com.au/~mark/software/lua-cjson.php ), [Zeroday ](https://github.com/funshine ) | [Zeroday ](https://github.com/funshine ) | [cjson ](../../app/modules/cjson.c ) |
2016-01-06 01:51:48 +01:00
The JSON support module. Allows encoding and decoding to/from JSON.
Please note that nested tables can require a lot of memory to encode. To catch out-of-memory errors, use `pcall()` .
## cjson.encode()
2016-01-09 21:22:39 +01:00
Encode a Lua table to a JSON string. For details see the [documentation of the original Lua library ](http://kyne.com.au/~mark/software/lua-cjson-manual.html#encode ).
2016-01-06 01:51:48 +01:00
####Syntax
`cjson.encode(table)`
####Parameters
2016-01-08 23:39:50 +01:00
`table` data to encode
2016-01-06 01:51:48 +01:00
While it also is possible to encode plain strings and numbers rather than a table, it is not particularly useful to do so.
####Returns
2016-01-08 23:39:50 +01:00
JSON string
2016-01-06 01:51:48 +01:00
####Example
```lua
ok, json = pcall(cjson.encode, {key="value"})
if ok then
print(json)
else
print("failed to encode!")
end
```
2016-01-08 23:39:50 +01:00
2016-01-06 01:51:48 +01:00
## cjson.decode()
2016-01-09 21:22:39 +01:00
Decode a JSON string to a Lua table. For details see the [documentation of the original Lua library ](http://kyne.com.au/~mark/software/lua-cjson-manual.html#_decode ).
2016-01-06 01:51:48 +01:00
####Syntax
`cjson.decode(str)`
####Parameters
2016-01-08 23:39:50 +01:00
`str` JSON string to decode
2016-01-06 01:51:48 +01:00
####Returns
2016-01-08 23:39:50 +01:00
Lua table representation of the JSON data
2016-01-06 01:51:48 +01:00
####Example
```lua
t = cjson.decode('{"key":"value"}')
for k,v in pairs(t) do print(k,v) end
2016-03-05 10:47:01 +01:00
```