Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to a valid json in rust

I am very new to rust with a background in javaScript and i am not able to go through a silly problem that this is "How to JSON.parse in Rust?"

I have a string "{\"first\":\"one\",\"second\":\"two\"}" which is a &str type, and i want an object {first:"one",second:"two"}.

I googled multiple links and am still stuck at this point.

tried approaches -

  1. let mut object: Value = serde_json::from_str(abc).unwrap();

    error - the trait bound api::Value: Deserialize<'_> is not satisfied

  2. converting it to string and Option by Some(string.as_deref())

  3. (Rust- JSON) How to convert &str to JSON response in rust?

  4. https://users.rust-lang.org/t/how-to-convert-a-string-type-to-a-json-object/72142

like image 707
Lakshay Kalra Avatar asked Oct 27 '25 08:10

Lakshay Kalra


1 Answers

There are many ways to parse a JSON string, but usually it does indeed involve serde and serde_json.

If you just want a simple serde_json::Value object, this works:

fn main() {
    let json_str = r#"{"first":"one","second":"two"}"#;
    let json_val: serde_json::Value = serde_json::from_str(json_str).unwrap();

    println!("{:#?}", json_val);
}
Object {
    "first": String("one"),
    "second": String("two"),
}

If you want something more sophisticated, like a struct that actually contains first and second members, you can parse it into a serde derived struct:

use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct MyValue {
    first: String,
    second: String,
}

fn main() {
    let json_str = r#"{"first":"one","second":"two"}"#;
    let my_value: MyValue = serde_json::from_str(json_str).unwrap();

    println!("{:#?}", my_value);
}
MyValue {
    first: "one",
    second: "two",
}

If you don't want a struct or Value at all and instead want a simple HashMap<String, String>, do this:

use std::collections::HashMap;

fn main() {
    let json_str = r#"{"first":"one","second":"two"}"#;
    let my_dict: HashMap<String, String> = serde_json::from_str(json_str).unwrap();

    println!("{:#?}", my_dict);
}
{
    "first": "one",
    "second": "two",
}

The possibilities of serde_json::from_str are endless. Just figure out what tasks you want to perform with the data, and then choose the appropriate data type ;)

like image 157
Finomnis Avatar answered Oct 28 '25 21:10

Finomnis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!