Serialise json data while keeping formatting?


#1

Hi

I have some serde json data and I am trying to same it to a file with formatting. However, all I can achieve in writing with all the formatting removed.

My code is like


        let mut save_data : serde_json::Value = json!(data);

        let pretty_data = serde_json::to_string_pretty(&save_data).unwrap();
     
        match file.write_all(pretty_data.as_bytes()) {

            Err(why) => {
                panic!("couldn't write to {}: {}", display, why.description())
            },
            Ok(_) => println!("successfully wrote to {}", display),
        }

How can I write some json keeping all the indents and new lines etc ?

Thanks


#2

Have you tried https://docs.serde.rs/serde_json/fn.to_writer_pretty.html?


#3

Think that worked. I think I was being silly and looking a the wrong file created. :frowning: Sorry


#4

Yeah, I think your old code should work as well - to_writer_pretty just saves you from materializing a String, I believe.