1
0
mirror of https://github.com/jht5945/prettyjson.git synced 2025-12-27 17:20:05 +08:00

add pretty json replace

This commit is contained in:
2019-07-28 11:09:20 +08:00
parent 003f3aad85
commit b4c38ebc7d

View File

@@ -4,7 +4,7 @@ extern crate json;
extern crate rust_util; extern crate rust_util;
use std::{ use std::{
fs::File, fs::{self, File},
io::{ io::{
self, self,
prelude::*, prelude::*,
@@ -32,6 +32,7 @@ fn read_to_string(read: &mut Read) -> XResult<String> {
struct Options { struct Options {
version: bool, version: bool,
replace_file: bool,
tab_width: u16, tab_width: u16,
file: String, file: String,
} }
@@ -39,6 +40,7 @@ struct Options {
fn main() { fn main() {
let mut options = Options { let mut options = Options {
version: false, version: false,
replace_file: false,
tab_width: 4u16, tab_width: 4u16,
file: String::new(), file: String::new(),
}; };
@@ -47,6 +49,7 @@ fn main() {
ap.set_description("prettyjson - command line JSON pretty tool."); ap.set_description("prettyjson - command line JSON pretty tool.");
ap.refer(&mut options.tab_width).add_option(&["-w", "--tab-width"], Store, "Tab width, default 4"); ap.refer(&mut options.tab_width).add_option(&["-w", "--tab-width"], Store, "Tab width, default 4");
ap.refer(&mut options.version).add_option(&["-v", "--version"], StoreTrue, "Print version"); ap.refer(&mut options.version).add_option(&["-v", "--version"], StoreTrue, "Print version");
ap.refer(&mut options.replace_file).add_option(&["-R", "--replace-file"], StoreTrue, "Replace file");
ap.refer(&mut options.file).add_argument("FILE", Store, "FILE"); ap.refer(&mut options.file).add_argument("FILE", Store, "FILE");
ap.parse_args_or_exit(); ap.parse_args_or_exit();
} }
@@ -86,5 +89,17 @@ fn main() {
}, },
}; };
println!("{}", json::stringify_pretty(json_object, options.tab_width)); let pretty_json = json::stringify_pretty(json_object, options.tab_width);
println!("{}", pretty_json);
if options.file.len() > 0 && options.replace_file {
match fs::write(&options.file, pretty_json) {
Err(err) => {
print_message(MessageType::ERROR, &format!("Write JSON file failed: {}", err));
},
Ok(_) => {
print_message(MessageType::OK, "Write JSON file success.");
},
}
}
} }