-
-
Notifications
You must be signed in to change notification settings - Fork 131
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to convert json to mlua::Value
like c-json.decode
#419
Comments
This usage is to register the local value = app.json_decode('{"id":123, "name":"foo"}')
print(value.name) |
Finally, I solved the problem with a layer of intermediate transformations: fn main() {
let s = r#"
{
"id": 123,
"name": "foo"
}
"#;
let lua = mlua::Lua::new();
let tmp: serde_json::Value = serde_json::from_str(&s).unwrap();
let value = json_to_lua_value(&lua, tmp).unwrap();
println!("{:?}", value);
}
fn json_to_lua_value(lua: &mlua::Lua, json_value: serde_json::Value) -> mlua::Result<mlua::Value> {
match json_value {
serde_json::Value::Null => Ok(mlua::Value::Nil),
serde_json::Value::Bool(b) => Ok(mlua::Value::Boolean(b)),
serde_json::Value::Number(n) => {
if let Some(i) = n.as_i64() {
Ok(mlua::Value::Integer(i))
} else if let Some(f) = n.as_f64() {
Ok(mlua::Value::Number(f))
} else {
Err(mlua::Error::RuntimeError("Invalid JSON number".into()))
}
}
serde_json::Value::String(s) => Ok(mlua::Value::String(lua.create_string(s)?)),
serde_json::Value::Array(arr) => {
let table = lua.create_table()?;
for (i, v) in arr.iter().enumerate() {
table.set(i + 1, json_to_lua_value(lua, v.clone())?)?;
}
Ok(mlua::Value::Table(table))
}
serde_json::Value::Object(obj) => {
let table = lua.create_table()?;
for (k, v) in obj.iter() {
table.set(k.as_str(), json_to_lua_value(lua, v.clone())?)?;
}
Ok(mlua::Value::Table(table))
}
}
} |
Isn't there a better interface for this usage? That is, it can be converted directly, without the need for a middle layer conversion |
Yes, use can use An example: https://github.com/mlua-rs/mlua/blob/master/examples/serialize.rs#L49 |
Example code, it will compile with an error:
The error messsage:
The text was updated successfully, but these errors were encountered: