Json encode function

Defold has already the json decode function in the api, but it strangely doesn’t have a json encode function. I know, there are many external lua modules for this, but it would be nice to have it already in defold api since the json encoding is already present.

3 Likes

I agree that a json.encode function would be very convenient, BUT I’m willing to bet a lot of money that which ever json.encode function that we decide to implement will not be sufficient for everyone for the simple reason that JSON cannot represent every Lua structure. Take a look at the following Lua user wiki page: http://lua-users.org/wiki/JsonModules

You will notice that there’s a ton of different implementations and if you scroll down to the section on “Edge cases for encoding” you’ll see that there’s a bunch of different issues. The most important edge case is the handling of an empty table. Should this table be encoded as an empty JSON object or an empty JSON array?

1 Like

Well, it’ s more complex than it seems, but as we can see some encode module works well with some edge cases and even have different speed. Maybe the better suitable one is dkjson if you check the tests in your link, but we have another popoular choice, CJSON, which solves your problem because it decodes JSON null as a Lua null pointer and then you can compare to a variable called cjson.null for convenience to check if the value compared is a null value. Another option would be to integrate many different types of encoding in the api so that the developer can choise relying on his table structure.