Why do I get a list of numbers instead of JSON when using the Twitch API via Rust?

我的梦境 提交于 2019-12-24 20:23:10

问题


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


回答1:


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).



来源:https://stackoverflow.com/questions/34279141/why-do-i-get-a-list-of-numbers-instead-of-json-when-using-the-twitch-api-via-rus

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!