Skip to content

Commit 218729d

Browse files
committed
Add set_array_metatable option to json decoder
1 parent a0aa27e commit 218729d

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

src/json.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ use std::sync::Arc;
33

44
use mlua::{
55
AnyUserData, Error as LuaError, ExternalResult, Function, Integer as LuaInteger, IntoLuaMulti, Lua,
6-
LuaSerdeExt, MetaMethod, MultiValue, Result, String as LuaString, Table, UserData, UserDataMethods,
7-
UserDataRefMut, Value,
6+
LuaSerdeExt, MetaMethod, MultiValue, Result, SerializeOptions, String as LuaString, Table, UserData,
7+
UserDataMethods, UserDataRefMut, Value,
88
};
99
use ouroboros::self_referencing;
1010
use serde::{Serialize, Serializer};
@@ -188,9 +188,15 @@ struct LuaJsonMapIter {
188188
iter: serde_json::map::Iter<'this>,
189189
}
190190

191-
fn decode(lua: &Lua, data: StringOrBytes) -> Result<StdResult<Value, String>> {
191+
fn decode(lua: &Lua, (data, opts): (StringOrBytes, Option<Table>)) -> Result<StdResult<Value, String>> {
192+
let opts = opts.as_ref();
193+
let mut options = SerializeOptions::new();
194+
if let Some(enabled) = opts.and_then(|t| t.get::<bool>("set_array_metatable").ok()) {
195+
options = options.set_array_metatable(enabled);
196+
}
197+
192198
let json: serde_json::Value = lua_try!(serde_json::from_slice(&data.as_bytes_deref()).into_lua_err());
193-
Ok(Ok(lua.to_value(&json)?))
199+
Ok(Ok(lua.to_value_with(&json, options)?))
194200
}
195201

196202
fn decode_native(lua: &Lua, data: StringOrBytes) -> Result<StdResult<Value, String>> {

tests/lua/json_tests.lua

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ testing:test("decode", function(t)
3131
value, err = json.decode("{a:1}")
3232
t.assert_eq(value, nil)
3333
t.assert(err:find("key must be a string"), "unexpected error message: " .. err)
34+
35+
-- No array metatable by default
36+
value, err = json.decode("[1,2,3]", { set_array_metatable = false })
37+
t.assert_eq(err, nil)
38+
t.assert_eq(type(value), "table", "value is not a table")
39+
t.assert_eq(getmetatable(value), nil, "array metatable is set")
3440
end)
3541

3642
-- Test decode to native object

0 commit comments

Comments
 (0)