Skip to content

Instantly share code, notes, and snippets.

@haochuan
Created February 10, 2020 23:41
Show Gist options
  • Select an option

  • Save haochuan/dbef73c2f3f53d3e161b72c46438ebda to your computer and use it in GitHub Desktop.

Select an option

Save haochuan/dbef73c2f3f53d3e161b72c46438ebda to your computer and use it in GitHub Desktop.
pub fn run() {
let contents = read_to_string("test-package.json").expect("Failed to read json file");
println!("{}", contents);
let indent = detect_indent::detect_indent(&contents);
let is_end_with_newline = contents.ends_with('\n');
let mut v: serde_json::Value =
serde_json::from_str(&contents).expect("Failed to parse json file");
println!("{:?}", v);
if let Some(map) = v.as_object_mut() {
println!("{:?}", map);
let insersion =
serde_json::to_value("0.9.9").expect("Failed to convert insertion into json");
map.insert("version".to_string(), insersion);
let mut file = File::create("test-package.json").expect("Failed to create json file");
let formatter = serde_json::ser::PrettyFormatter::with_indent(indent.indent().as_bytes());
let mut ser = serde_json::Serializer::with_formatter(&file, formatter);
map.serialize(&mut ser).expect("Failed to indent json");
// append the empty line if the original package.json has one
if is_end_with_newline {
writeln!(file).expect("Failed to write new line in json");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment