You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: markdown/api/library/json/encode.markdown
+32-1Lines changed: 32 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -35,11 +35,42 @@ _[Table][api.type.Table]._ Lua table containing optional directives to the JSON
35
35
3. All control chars are encoded to `\uXXXX` format, for example `"\021"` encodes to `"\u0015"`.
36
36
4. All JSON `\uXXXX` chars are decoded to chars (`0`-`255` byte range only).
37
37
5. JSON single line `//` and `/* */` block comments are discarded during decoding.
38
-
6.Numerically indexed Lua arrays are encoded to JSON lists, for example `[1,2,3]`.
38
+
6.A Lua table is encoded to a JSON array when all of its keys are positive integers (gaps are permitted), for example `[1,2,3]`. The presence of any key that isn't a positive integer forces the entire table to be encoded as a JSON object instead.
39
39
7. Lua dictionary tables are converted to JSON objects, for example `{"one":1,"two":2}`.
40
40
8. By default, JSON nulls are decoded to Lua `nil` and treated by Lua in the normal way (for example, they appear not to exist — see [json.decode()][api.library.json.decode]).
41
41
42
42
43
+
## Gotchas
44
+
45
+
JSON has two collection types, arrays (`[]`) and objects (`{}`), but Lua has only the table, so `json.encode()` has to pick one. A table is encoded as an array when all of its keys are positive integers (gaps are permitted), and as an object the moment any non-integer key is present.
46
+
47
+
Because JSON object keys are always strings, every key in an object-encoded table is stringified, integer keys included. Adding a single key that isn't a positive integer therefore changes how the entire table is encoded, including its positive-integer keys:
1.__Round-tripping does not preserve integer keys.__`json.decode( json.encode( t2 ) )` returns a table keyed by the strings `"1"`, `"2"`, `"3"`, not the integers `1`, `2`, `3`. Code that later indexes with `t[1]` will get `nil`.
71
+
2.__Key order in an object is not guaranteed.__ Do not rely on the position of keys in the encoded string.
0 commit comments