mpx / lua-cjson

Lua CJSON is a fast JSON encoding/parsing module for Lua

Home Page:https://kyne.au/~mark/software/lua-cjson.php

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

cjson.decode crashed if wrong json passed

alex-roman opened this issue · comments

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?

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.

Thank you! Exactly what I need!