Skip to content

Instantly share code, notes, and snippets.

@danneu
Created September 11, 2018 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danneu/401d8f18941e1297f15f26be480710d3 to your computer and use it in GitHub Desktop.
Save danneu/401d8f18941e1297f15f26be480710d3 to your computer and use it in GitHub Desktop.
#[derive(Deserialize, Debug)]
pub struct Submission {
#[serde(rename = "id")]
pub thing_id: String,
pub author: String,
pub title: String,
pub created_utc: f32,
pub score: i32,
pub url: String,
}
// Payload:
//
// [ { data: { children: [ { data: Submission } ] } }
// , {}
// ]
//
// Path: [0] -> .data -> .children -> [0] -> .data
pub fn fetch_submission(client: &Client, thing_id: &str) -> Result<Option<Submission>, Error> {
let url: Url = format!("https://www.reddit.com/{}.json", thing_id).parse().unwrap();
let mut response = client.get(url).send()?;
assert!(response.status().is_success());
let body = response.json::<serde_json::Value>()?;
let submission: Option<Submission> = match body {
Value::Array(arr) => {
match arr.get(0) {
Some(Value::Object(map)) => {
match map.get("data") {
Some(Value::Object(map)) => {
match map.get("children") {
Some(Value::Array(arr)) => {
match arr.get(0) {
Some(Value::Object(map)) => {
match map.get("data") {
Some(Value::Object(map)) => {
serde_json::from_value(Value::Object(map.clone()))?
},
_ => None
}
},
_ => None
}
},
_ => None
}
},
_ => None
}
},
_ => None
}
},
_ => None
};
Ok(submission)
}
@danneu
Copy link
Author

danneu commented Sep 11, 2018

let submission: Option<Submission> = serde_json::from_value(body
    .get(0)?
    .get("data")?
    .get("children")?
    .get(0)?
    .get("data")?
    .take()
)?;

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