-
-
Notifications
You must be signed in to change notification settings - Fork 2
Fluid JSON API
The JSON API provides encoding and decoding functionality for moving data between JSON strings and Lua tables.
The API can be loaded with the line:
require 'json'
This expects the following to be true of any tables being encoded:
- They only have string or number keys. Number keys must be represented as strings in json; this is part of the json spec.
- They are not recursive. Such a structure cannot be specified in json.
A Lua table is considered to be an array if and only if its set of keys is a consecutive sequence of positive integers starting at 1. Arrays are encoded like so: [2, 3, false, "hi"]
. Any other type of Lua table is encoded as a json object, encoded like so: {"key1": 2, "key2": false}
.
Because the Lua nil value cannot be a key, and as a table value is considerd equivalent to a missing key, there is no way to express the json "null" value in a Lua table. The only way this will output "null" is if your entire input obj is nil itself.
An empty Lua table, {}, could be considered either a json object or array - it's an ambiguous edge case. We choose to treat this as an object as it is the more general type.
None of the above considerations is a limitation of this code. Rather, it is what we get when we completely observe the json specification for as arbitrary a Lua object as json is capable of expressing.
This function decodes json, with the exception that it does not pay attention to \u-escaped unicode code points in strings.
It is difficult for Lua to return null as a value. In order to prevent the loss of keys with a null value in a json string, this function uses the one-off table value json.null (which is just an empty table) to indicate null values. This way you can check if a value is null with the conditional val == json.null
.
API originally written by @tylerneylon for the public domain.