diff --git a/Cargo.toml b/Cargo.toml index f3d9d23..b12da15 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,4 +11,6 @@ reqwest = { version = "0.10", features = ["blocking", "json"] } tokio = { version = "0.2", features = ["full"] } url = "2.1" http = "0.2" -nipper = "0.1.8" \ No newline at end of file +nipper = "0.1.8" +serde_json = "1.0" +serde = "1.0" \ No newline at end of file diff --git a/src/request.rs b/src/request.rs index 4814576..1945e5a 100644 --- a/src/request.rs +++ b/src/request.rs @@ -1,7 +1,8 @@ -use crate::response; use http::status::StatusCode; use url::{ParseError, Url}; +use crate::response; + pub trait RequestBase { fn new(url: &'static str) -> Result where diff --git a/src/response.rs b/src/response.rs index be5ea7e..1cc3f27 100644 --- a/src/response.rs +++ b/src/response.rs @@ -1,7 +1,9 @@ -use crate::selector::SelectorBase; use http::StatusCode; +use serde_json::{Result, Value}; use url::Url; +use crate::selector::SelectorBase; + #[derive(Debug)] pub struct Response { pub text: String, @@ -15,6 +17,14 @@ impl SelectorBase for Response { } fn html(&self) -> String { - format!("{}", self.text) + self.text.clone() + } +} + +impl Response { + pub fn to_json(&self) -> Result { + let plain_text: &[u8] = self.text.as_ref(); + let json = serde_json::from_slice(plain_text)?; + Ok(json) } } diff --git a/tests/unit_tests.rs b/tests/unit_tests.rs index 3bc9853..1dc1095 100644 --- a/tests/unit_tests.rs +++ b/tests/unit_tests.rs @@ -75,4 +75,13 @@ fn complex_selectors() { assert_eq!(node.content(), "link"); } } + assert!(sel.css_once::("h1").is_none()); +} + +#[test] +fn simple_json_test() { + let req: Request = RequestBase::new("https://httpbin.org/json").unwrap(); + let resp = req.launch().to_json().expect("cannot parse json"); + + assert_eq!(resp["slideshow"]["title"], "Sample Slide Show"); }