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

Nested json decode error

leopeng1995 opened this issue · comments

{"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.

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

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 [[\\]].