mpx / lua-cjson

Lua CJSON is a fast JSON encoding/parsing module for Lua
https://kyne.au/~mark/software/lua-cjson.php
MIT License
933 stars 478 forks source link

cjson.decode crashed if wrong json passed #32

Closed alex-roman closed 8 years ago

alex-roman commented 8 years ago

Hi there!

First of all thank you for a library! Here is some code I can't explain to myself:

00:59 ar@alexroman-XPS8700[~]$ cat cjson.lua 
#!/usr/bin/lua

local cjson = require "cjson"
local badjson = "Just a string"

print(cjson.decode(badjson))
00:59 ar@alexroman-XPS8700[~]$ ./cjson.lua 
/usr/bin/lua: ./cjson.lua:6: Expected value but found invalid token at character 1
stack traceback:
    [C]: in function 'decode'
    ./lua-cjson-bug.lua:6: in main chunk
    [C]: ?
00:59 ar@alexroman-XPS8700[~]$

Some my clients send wrong JSON and it cause crash of script. If it's a correct behavior I'll be happy to know how can I handle this error?

mpx commented 8 years ago

Decode is failing since "Just a string" is not a JSON string - it needs quotes. Eg:

'"Just a string"'
"\"Just a string\""

If you need to capture the error from invalid requests you can use cjson.safe. Eg:

local cjson_safe = require "cjson.safe"
result, err = cjson.safe("invalid json")

err will be nil on success, or contain the error message.

The manual has further details.

alex-roman commented 8 years ago

Thank you! Exactly what I need!