Skip to content

Conversation

@LewisJEllis
Copy link
Contributor

Based on #18, will rebase after that's merged; until then just look at latest commit.

This still needs docs, some tests, and some better failsafes, but I've tested it manually and it seems to work great. A bit WIP, but the core of it, including approach for dealing with non-json-serializable values and deeply nested tables, is done; open to comments on implementation strategy/conf options/etc.

To deal with non-json-serializable values, I made a json_prep_value helper which takes a lua value and makes it safe to pass to cjson.encode by either tostringing or dropping pieces as necessary to comply with cjson's specified requirements, mainly:

JSON object keys are always strings. Hence cjson.encode only supports table keys which are type number or string. All other types will generate an error.

and

The remaining Lua types will generate an error:

  • function
  • lightuserdata (non-NULL values)
  • thread
  • userdata

There are still a couple cases missing that I need to add, mainly NaN/Infinity, and I also want to have a better failsafe for any general unexpected case where cjson.encode fails.

return json_prep_table(v, max_depth - 1)
end
else
return v
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a defensive programming technique, I would consider the fallback to use tostring and return the raw value only for types that are known to be serializable with JSON (number and string in this case).

For instance, this code does not behaves correctly with cdata objects in LuaJIT.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants