Error("invalid type: map, expected a sequence", line: 1, column: 1),
0{
symbol "ETHBTC"
priceChange "0.00068700"
priceChangePercent "0.874"
weightedAvgPrice "0.07908580"
prevClosePrice "0.07864600"
lastPrice "0.07933400"
lastQty "0.18460000"
bidPrice "0.07933400"
bidQty "4.49640000"
askPrice "0.07933500"
askQty "54.13430000"
openPrice "0.07864700"
highPrice "0.07945000"
lowPrice "0.07846100"
volume "56892.20330000"
quoteVolume "4499.36548634"
openTime 1662288072375
closeTime 1662374472375
firstId 369847410
lastId 370015037
count 167628
}
My request function makes a cURL request and receives the above JSON. I then use serde_json to deserialize the JSON>. Please help in solving this issue
main.rs
use serde::Deserialize;
use std::error::Error;
#[derive(Deserialize, Debug)]
struct Peers {
num: Vec<Peer>,
}
#[derive(Deserialize, Debug)]
struct Peer {
symbol: String,
count: u32,
}
fn get_node(url: &str) -> Result<Peer, Box<dyn Error>> {
let response = ureq::get(url).call()?.into_string()?;
let node: Peers = serde_json::from_str(&response)?;
dbg!(node);
todo!()
}
fn main() {
let url = "https://api.binance.com/api/v1/ticker/24hr";
let num = get_node(url);
dbg!(num);
todo!()
}
I'm getting the following error message in my terminal
num = Err(
Error("invalid type: map, expected a sequence", line: 1, column: 1),
)
thread 'main' panicked at 'not yet implemented',
note: run with `RUST_BACKTRACE=1` environment variable to display a
I'm certain I'm making a stupid mistake in deserializing my JSON structure, I've tried a number of permutations and combinations but I couldn't get anything to work. Please help me solving this issue in Rust
Your issue is that you're trying to deseralize the top level array ([{...}, {..}]) into a struct (Peers
).
You noted in your struct that it should be a vec, which is the right thing to deserialize into, so you're close. All you need to do is change your:
let node : Peers = serde_json::from_str(&response)?;
into
let node : Vec<Peer> = serde_json::from_str(&response)?;
If you want to keep your Peers struct in the function, you could do something like:
let peers = Peers {
num: serde_json::from_str(&response)?,
};
By the way ureq
has a tool that will simplify your usage of serde_json.