-
I'm trying to convert Python dict to Rust serde_json::Value, but it seems that PyDict.tostring has turned all JSON keys into single quotes, so serde_json cannot parse it. How to fix it? let x = Python::with_gil(|py| {
let locals = PyDict::new_bound(py);
Python::run_bound(py, r#"
a= {"a":1, "b":2}
"#, None, Some(&locals)).unwrap();
let ret = locals.get_item("a").unwrap().unwrap();
println!("a value: {}", ret.to_string());
if ret.is_instance_of::<PyDict>() {
let s = ret.downcast::<PyDict>().unwrap().to_string();
DataValue::Json(serde_json::from_str(s.as_str()).unwrap())
} else {
DataValue::String(ret.to_string())
}
}
);
println!("result: {:?}", x); Output:
|
Beta Was this translation helpful? Give feedback.
Answered by
LilyFoote
Oct 16, 2024
Replies: 1 comment 1 reply
-
You could try this: let x = Python::with_gil(|py| {
let locals = PyDict::new_bound(py);
Python::run_bound(py, r#"
import json
a= json.dumps({"a":1, "b":2})
"#, None, Some(&locals)).unwrap();
let ret = locals.get_item("a").unwrap().unwrap();
let s = ret.extract::<String>().unwrap();
DataValue::Json(serde_json::from_str(s.as_str()).unwrap())
}
);
println!("result: {:?}", x); I haven't tested this myself, so you may need to tweak it a bit. You could also look into the |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
0x3E6
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could try this:
I haven't tested this myself, so you may need to tweak it a bit.
You could also look into the
pythonize
crate, which might work for you.