【问题标题】:Adding a trailing linefeed to json向 json 添加尾随换行符
【发布时间】:2021-03-23 18:45:37
【问题描述】:

我正在使用 serde 将一些数据序列化为 json 格式的文件:

let json = serde_json::to_string_pretty(&data).unwrap();
std::fs::write(&path, &json).expect("Unable to write json file");

向文件添加尾随换行符的最佳方法是什么?

【问题讨论】:

    标签: rust serde


    【解决方案1】:

    std::fs::write 只是一个方便的 API。您可以自己写入文件,在这种情况下,您可以在json_serde 完成写入后添加一个换行符,例如:

    pub fn save(path: impl AsRef<Path>, data: &impl Serialize) -> std::io::Result<()> {
        let mut w = BufWriter::new(File::create(path)?);
        serde_json::to_writer_pretty(&mut w, data)?;
        w.write(b"\n")?;
        w.flush()?;
        Ok(())
    }
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-01
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      相关资源
      最近更新 更多