-
-
Notifications
You must be signed in to change notification settings - Fork 2
Tiri JSON API
The JSON API provides encoding and decoding functionality for moving data between JSON strings and Tiri tables/arrays.
The API can be loaded with the line:
import 'json'result = json.encode(Value, [ErrorCallback], AsKey)
Encodes a Value into a JSON string and returns it. The following types are supported:
| Type | JSON Output |
|---|---|
array |
JSON array, e.g. [2, 3, false, "hi"]
|
table |
JSON object, e.g. {"key1": 2, "key2": false}
|
string |
Quoted string with special characters escaped |
number |
Number literal (quoted if used as an object key) |
boolean |
true or false
|
nil |
null |
function |
The literal string function
|
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.
Native Tiri arrays are encoded as JSON arrays. Tables are encoded as JSON objects.
Because the nil value cannot be a key, and as a table value is considered equivalent to a missing key, there is no way to express the JSON "null" value in a table. The only way this will output "null" is if your entire input value is nil itself.
The optional ErrorCallback parameter accepts a function that will be called on encoding errors (e.g. unsupported types, or attempting to encode an array or table as an object key). If not provided, errors are raised with error().
result = json.decode(String, Pos)
Decodes a JSON string into Tiri values. Returns two values: the decoded result and the position after the last parsed character.
JSON objects are decoded as Tiri tables, and JSON arrays are decoded as Tiri arrays. The optional Pos parameter specifies the starting position within the string (defaults to 0).
This function does not interpret \u-escaped unicode code points in strings.
It is difficult for Tiri 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 is json.null. If you have control over the data, avoid null values to begin with.
An empty table used as a sentinel value to represent JSON null in decoded output. Test for it with:
if val is json.null then
-- handle null
endAPI originally written by @tylerneylon for the public domain.