Search code examples
jsonrusterror-handlingtwitch

Manipulate Result type with JSON as content


This is a follow-up on the question Why do I get a list of numbers instead of JSON when using the Twitch API via Rust? If I use the solution suggested in the previous post:

Use the response.get_body() method to get a list of byte number which can be converted to a Result with from_utf8() method.

This returns a Result with everything in it. I'm not sure how to manipulate it. I was hoping I could use it like an array but the docs and rustbyexample don't seem to explain it. What is the purpose of a Result type?

This is the exact response that I'm getting from the body after converting it to UTF-8.


Solution

  • The Result type does not help you here – it just stores arbitrary data and is used for error handling (instead of exceptions). But you can use the rustc_serialize crate to parse the string returned by the Result:

    extern crate rustc_serialize;
    use rustc_serialize::json::Json;
    
    fn main() {
        let response_result = /* ... */;
        let data = response_result.unwrap();
        let json = Json::from_str(&data).unwrap();
        println!("{}", json.find("status").unwrap());
    }