pub fn to_json_value(
value: LuaValue<'_>,
opts: impl Borrow<JsonConversionOptions>,
) -> Result<Value, JsonConversionError>Expand description
Converts a LuaValue into a serde_json::Value.
§Caveats
There are a number of caveats to the conversion process, which may
result in data loss, changes or strangely-formed data, such that running
from_json_value(to_json_value(a)) may not return the same value.
The process aims to follow Lua’s conventions when coercing to JSON.
serde_json::Value always uses owned types, so conversion may result in a copy for all
Cow-based types (strings).
§Floating points
f64::INFINITY, f64::NEG_INFINITY and f64::NAN cannot be represented in JSON, and
return JsonConversionError.
§Strings
Lua strings are
assumed to be encoded as UTF-8, and converted to a String.
If the string is not valid UTF-8, this will return JsonConversionError::Utf8Error (unless
JsonConversionOptions::lossy_string is true).
Note: Lua strings are equivalent to Rust’s [u8] type, and have no defined encoding.
This can result in unexpected behaviour if the string is encoded differently or contains
binary data, but could be interpreted as UTF-8.
JSON has no standard syntax to express arbitrary binary data, and always encoding Lua strings with something like Base64 would make the outputs difficult to use.
§Tables
Lua does not have a distinct Array-like type, only Object. This method will attempt to
convert a table that looks like an Array into one:
-
An empty table will be converted to an empty object.
-
A table containing only implicitly-keyed entries will be converted to an array.
-
A table containing one or more explicitly-keyed entries will be converted to an object.
-
Tables with a mix of explicitly and implicitly-keyed entries will key implicitly-keyed values in the same as Lua, with consecutive integers starting counting at
1, without regard for explicitly-keyed entries.This means
{[1] = 1, 2, 3, [2] = 4}will result in{"1": 2, "2": 4} -
Table keys are converted to strings when expressed as JSON:
- Lua string keys are converted in the same way as other strings
nilis converted to the string"nil"trueandfalseare converted to the strings"true"and"false"- integers and floating points are converted to strings with Rust formatting conventions
- Tables keyed with a table will return
JsonConversionError::TableKeyedWithTable
-
Entries of tables with the same key defined multiple times will be silently overwritten (later entries take precedence).
Note: serde_json may not preserve the order of keys in an object.