diff options
author | Benedikt Peetz <benedikt.peetz@b-peetz.de> | 2025-06-17 09:04:12 +0200 |
---|---|---|
committer | Benedikt Peetz <benedikt.peetz@b-peetz.de> | 2025-06-17 09:04:12 +0200 |
commit | 8d6eb786ee99e7b0c36736152e30a5f61cd34167 (patch) | |
tree | dbdf1d5add7df156b21ca39a670246c5df022458 /crates/yt_dlp/src/info_json.rs | |
parent | refactor(yt_dlp/progress_hook): Use public api via `__priv` module (diff) | |
download | yt-8d6eb786ee99e7b0c36736152e30a5f61cd34167.zip |
refactor(yt_dlp): Split the big `lib.rs` file up
Diffstat (limited to 'crates/yt_dlp/src/info_json.rs')
-rw-r--r-- | crates/yt_dlp/src/info_json.rs | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/crates/yt_dlp/src/info_json.rs b/crates/yt_dlp/src/info_json.rs new file mode 100644 index 0000000..db4616d --- /dev/null +++ b/crates/yt_dlp/src/info_json.rs @@ -0,0 +1,50 @@ +use rustpython::vm::{ + PyRef, VirtualMachine, + builtins::{PyDict, PyStr}, +}; + +pub type InfoJson = serde_json::Map<String, serde_json::Value>; + +pub fn json_loads( + input: serde_json::Map<String, serde_json::Value>, + vm: &VirtualMachine, +) -> PyRef<PyDict> { + let json = vm.import("json", 0).expect("Module exists"); + let loads = json.get_attr("loads", vm).expect("Method exists"); + let self_str = serde_json::to_string(&serde_json::Value::Object(input)).expect("Vaild json"); + let dict = loads + .call((self_str,), vm) + .expect("Vaild json is always a valid dict"); + + dict.downcast().expect("Should always be a dict") +} + +/// # Panics +/// If expectation about python operations fail. +pub fn json_dumps( + input: PyRef<PyDict>, + vm: &VirtualMachine, +) -> serde_json::Map<String, serde_json::Value> { + let json = vm.import("json", 0).expect("Module exists"); + let dumps = json.get_attr("dumps", vm).expect("Method exists"); + let dict = dumps + .call((input,), vm) + .map_err(|err| vm.print_exception(err)) + .expect("Might not always work, but for our dicts it works"); + + let string: PyRef<PyStr> = dict.downcast().expect("Should always be a string"); + + let real_string = string.to_str().expect("Should be valid utf8"); + + // { + // let mut file = File::create("debug.dump.json").unwrap(); + // write!(file, "{}", real_string).unwrap(); + // } + + let value: serde_json::Value = serde_json::from_str(real_string).expect("Should be valid json"); + + match value { + serde_json::Value::Object(map) => map, + _ => unreachable!("These should not be json.dumps output"), + } +} |