How convert JSON numbers to floating

I am at start of my journey whit Rust, and I am not able to convert a JSON number.
My JSON structure arrive from a TCL/TK form generator that write to stdout and is transferred to a Hash map:

	let data = String::from_utf8(output.stdout)?;
	println!("data:\n{}", data);
	println!("status: {}", output.status);
        let v:HashMap<String, Value> = serde_json::from_str(&data)?;
	if v.contains_key("Integer") {
//		let integer: f64 = from(v["Integer"]);
//		let integer: f64 = v["Integer"]::Number;
//		let integer: f64 = v["Integer"].as_f64();
//		let integer = v["Integer"].as_f64();

all the instructions I tried (except the first one) report an error; in the case of the first, the error is on the addition operation.

You can parse a string into a number with the_string.parse(). If you wish to use addition, you would need to first convert to number, then add.

Oh, it's a json value, not a string. I would recommend using as_f64, although you have to use unwrap to panic if it turns out not be to a valid float.

1 Like

When trying to diagnose a problem, it's always good to pay attention to what error you are getting. You never say.

1 Like

Thanks Alice but
let integer = v["Integer"].as_f64();
and not a floating number.

It returns Option<f64> because the operation might fail. Try v["Integer"].as_f64().unwrap().

Thanks Alice, it works

You may want to de-serialize using a struct instead. It will save you the parsing and it's performance is usually better.

use serde::{Deserialize};

pub struct MyData {
    #[serde(rename = "Integer")]
    i: f64,
    num: f64,
    dec_num: f64,

fn main() {
    let data = r#"{"Integer": 1.3, "num": 0.3, "dec_num": 3.4}"#;
    let obj: MyData = serde_json::from_str(data).unwrap();
    println!("Sum: {}", obj.i + obj.num + obj.dec_num);

Thanks Naim
your solution is intresting, I try to implement.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.