0

I'm playing around with the Twitch API in Rust, but I can't manage to get a correct JSON output from the response.

extern crate curl;

use curl::http;

fn main() {
    let url = "http://api.twitch.tv/kraken/channels/twitch";

    let resp = http::handle()
        .get(url)
        .exec().unwrap();

    /* Prints StatusCode and Headers correctly. Print Body (requested json as numbers) */
    println!("Code : {}\nHeaders : {:?}\nHeaders : {:?}\nBody : {:?}", 
        resp.get_code(), resp.get_header("content-length"), resp.get_headers(), resp.get_body());

    /* Prints everything after each other and prints json correctly */
    println!("{}", resp);
}

I don't understand why I get numbers as output instead of the JSON.

Example of output json:

[123, 34, 109, 97, 116, 117, 114, 101, 34, 58, 102, 97, 108]

Example of correct json:

{"mature":false,"status":"Twitch Weekly - 12/11/2015","broadcaster_language":"en"}

Example of the full output: https://bitbucket.org/snippets/adrianz/q88KM

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Adrian Z.
  • 904
  • 1
  • 12
  • 29

1 Answers1

4

The get_body function has signature:

pub fn get_body<'a>(&'a self) -> &'a [u8] {

That is, it is returning a slice of bytes, and printing such a slice prints them as numbers. The numbers are the raw values of the (ASCII) characters in the JSON, which can be viewed as a str (if they are UTF-8 encoded) via from_utf8:

fn main() {
    let b = [123_u8, 34, 109, 97, 116, 117, 114, 101, 34, 58, 102, 97, 108];

    println!("{:?}", std::str::from_utf8(&b));
}

Which outputs Ok("{\"mature\":fal"). i.e. the bytes are the first part of the JSON data you're expecting.

BTW, knowing the types of functions is a really useful thing, which you can do easily by running cargo doc --open, which will run rustdoc on your crate and all your dependencies, and then open it in your web-browser (if --open doesn't work, then navigating to /path/to/project/target/doc/curl/index.html in your web-browser should work too).

huon
  • 94,605
  • 21
  • 231
  • 225
  • I saw the signature indeed but I was not sure what I had to do with it. Thanks for the tips and the explanation. This should help me to get further. – Adrian Z. Dec 15 '15 at 00:51