Search code examples
jsonrusthyper

How do I split up data from a hyper JSON body so I have a hashmap with multiple keys and values?


I've managed to extract data from a POST method in hyper using the following:

use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method, Request, Response, Server};
use std::convert::Infallible;
use std::net::SocketAddr;
use tokio;

async fn handle(_req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
    match (_req.method(), _req.uri().path()) {
        (&Method::GET, "/") => Ok(Response::new(Body::from("this is a get"))),

        (&Method::POST, "/") => {
            let byte_stream = hyper::body::to_bytes(_req).await?;
            let _params = form_urlencoded::parse(&byte_stream)
                .into_owned()
                .collect::<HashMap<String, String>>();

However, the whole JSON body is just one key in the HashMap now. How do I split it up so I have a hashmap with multiple keys and values as opposed to one key that's the entire body?

[dependencies]
futures = "0.1"
hyper = "0.13"
pretty_env_logger = "0.3.1"
url = "2.1.1"
tokio = { version = "0.2", features = ["macros", "tcp"] }
bytes = "0.5"

Solution

  • There is a discrepancy between your description:

    However, the whole JSON body

    And your code:

    let _params = form_urlencoded::parse(&byte_stream)

    If your data is JSON then parse it as JSON, using the serde_json crate:

    let _params: HashMap<String, String> = serde_json::from_slice(&byte_stream).unwrap();