【问题标题】:Why do I get a list of numbers instead of JSON when using the Twitch API via Rust?当通过 Rust 使用 Twitch API 时,为什么我得到一个数字列表而不是 JSON?
【发布时间】:2016-03-20 15:33:47
【问题描述】:

我正在使用 Rust 中的 Twitch API,但我无法从响应中获得正确的 JSON 输出。

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);
}

我不明白为什么我得到的是数字而不是 JSON。

输出json示例:

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

正确的json示例:

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

完整输出示例:https://bitbucket.org/snippets/adrianz/q88KM

【问题讨论】:

  • 我对你的输出感到困惑:这是最后一个println!的输出?
  • 我可以为您更新一个确切的终端输出示例吗?最后一个println的输出就是status、headers和json合二为一。
  • 那太好了。
  • 根据branah.com/ascii-converter 那串整数等于{ " m a t u r e " : f a l
  • @erip 我已经用示例更新了它。

标签: json rust twitch


【解决方案1】:

get_body function 有签名:

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

也就是说,它返回一个字节切片,打印这样一个切片会将它们打印为数字。这些数字是 JSON 中 (ASCII) 字符的原始值,可以通过from_utf8 将其视为str(如果它们是 UTF-8 编码的):

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

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

哪个输出Ok("{\"mature\":fal")。即字节是您期望的 JSON 数据的第一部分。

顺便说一句,知道函数的类型是一件非常有用的事情,您可以通过运行 cargo doc --open 轻松完成,这将在您的 crate 和所有依赖项上运行 rustdoc,然后在您的网络浏览器中打开它(如果--open 不起作用,那么在您的网络浏览器中导航到/path/to/project/target/doc/curl/index.html 也应该起作用。

【讨论】:

  • 我确实看到了签名,但我不确定我必须用它做什么。感谢您的提示和解释。这应该有助于我走得更远。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 2012-08-01
  • 1970-01-01
  • 2019-06-07
  • 1970-01-01
相关资源
最近更新 更多