mpx / lua-cjson

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

handling totally invalid jsons #67

Open alexyuriev opened 5 years ago

alexyuriev commented 5 years ago

Hi,

Since this is not addressed in documentation I thought I would ask here - what's the "right" way of handling invalid JSONs without blowing up?

graywolf commented 2 years ago

I don't think there is nothing specific to this library regarding that. You either have the option of using cjson.safe (that is documented), or just protecting the call with pcall:

+   $ lua5.4
Lua 5.4.3  Copyright (C) 1994-2021 Lua.org, PUC-Rio
+> cjson = require 'cjson'
+> cjson_safe = require 'cjson.safe'
+> pcall(cjson.decode, "foo")
false   Expected value but found invalid token at character 1
+> cjson_safe.decode("foo")
nil     Expected value but found invalid token at character 1