Skip to content

Instantly share code, notes, and snippets.

@myksao
Last active October 5, 2023 22:31
Show Gist options
  • Save myksao/e98c215de383fcef69cc1fdfff41ca3a to your computer and use it in GitHub Desktop.
Save myksao/e98c215de383fcef69cc1fdfff41ca3a to your computer and use it in GitHub Desktop.
field and value extraction using serde json
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub fn extraction<T: Default + Serialize>(data: &T) -> Value {
let columns = serde_json::to_value(data.clone())
.unwrap()
.as_object()
.unwrap()
.keys()
.map(|key| key.to_string())
.collect::<Vec<String>>();
match serde_json::to_value(data) {
Ok(Value::Object(mut map)) => {
map.retain(|k, v| columns.contains(&k.to_string()) && !v.is_null());
Value::Object(map)
},
_ => Value::Null,
}
}
@myksao
Copy link
Author

myksao commented Oct 5, 2023

Add preserve_order and indexmap feature flag to serde_json

serde_json = { version = "1.0.107", features = ["preserve_order", "indexmap"] }
serde = { version = "1.0.188", features = ["derive"] }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment