mpx / lua-cjson

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

Nested json decode error #58

Closed leopeng1995 closed 6 years ago

leopeng1995 commented 6 years ago

{"status_code":503,"body":"{"code": 1, "message": "Service unavailable"}"}

I want to decode the statement above, but got Expected value but found invalid token at character 27 error. I tried another statement like below:

{"status_code":503,"body":{"code": 1, "message": "Service unavailable"}}

However there is same error. It looks like cjson does't support decode nested? Is there another solution? Thx.

pmusa commented 6 years ago

Your first statement is not a valid JSON, so I would indeed expect an error. However, your second statement is a valid JSON and looking at it, it should work.

I tested and it works just fine.

c = require"cjson"
s = '{"status_code":503,"body":{"code": 1, "message": "Service unavailable"}}'
l = c.decode(s)
for k,v in pairs(l) do print(k,v) end
leopeng1995 commented 6 years ago

Emmm, thx's a lot. That's work. The reason is the body was treated as string and handled by cjson.encode. So the " was translated to \".

I have another question about backslash.

local a = {"hosts":[".*\\.?example(?:-bar)?.com"]}
local b = cjson.decode(a)

The raw string is [[.*\.?example(?:-bar)?.com]].

It doesn't work and will get Expected value but found invalid escape code at character 14 error. How can I solve this issue? Thx.

Updated I used [[\]] to replace [[\\]].