Home Contents | # table.fromJson | JSON | Core4 Lua Commands

## SYNOPSIS

result, data = table.fromJson(text [, nullreplacer])

## DESCRIPTION

Decodes a JSON formatted string into a Lua table.

The decoder allows the top level value to have no name.

Both examples presented here are valid:

{ "sample" : "text", "number" : 17 }
"name" : { "sample" : "text", "number" : 17 }

Lua has no concept of a null value. By default, all JSON null values are replaced with nil. This makes them disappear from the result.

As a workaround a replacement value for JSON null can be passed as the second parameter. This is inserted whenever there is a null value in the source JSON data. The application can then check for this replacement value.

## RETURN VALUE

On success, the first result result, returns the top level name, or true if there was none. The second result data, returns a table with the decoded JSON data.

On failure, the first result result is nil. The second result is the index into the string where the first error was encountered.

## NULL VALUES

One way to not lose null values in the JSON data is to use a marker table. Begin by defining a global JsonNull object.

JsonNull = { } JsonNull.__tostring = function() return "null" end setmetatable(JsonNull, JsonNull)

This marker can now be used with the JSON codecs. The metatable trickery causes it to be printed as simply null.

>
print(JsonNull)
null

When working with the decoded JSON data, whenever a value equals JsonNull, the application knows there was a JSON null value.

local inputstring = '{ "example": null }' local result, data = table.fromJson(inputstring, JsonNull) if (data.example == JsonNull) then -- This is a null value end

Caution is advised, as such a marker table does NOT register as a boolean false value, which is unexpected.

## EXAMPLES

> > > > > > > > > > > > > > > > >
name, data = table.fromJson([[ "Product" : { "name" : "Foo", "id" : 1, "price" : 123, "tags" : [ "Bar", "Eek" ], "stock" : { "warehouse" : 300, "retail" : 20, "other" : null } }]]) print("name", name) print("data", table.tostring(data))
name Product data { id=1, name="Foo", price=123, tags={ "Bar", "Eek" }, stock={ warehouse=300, retail=20 } }

Note how the null value of "other" is missing, and how the order of fields inside the resulting table does not match the original JSON.

This is typical Lua behaviour and should not present an issue.

## SEE ALSO

table.toJson()