Skip to content

Commit d47cb10

Browse files
killerswanerickt
authored andcommitted
Pretty print JSON: indentation and newlines
1 parent 536cb90 commit d47cb10

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

src/libstd/json.rs

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,69 @@ fn to_writer(wr: io::Writer, j: Json) {
8686
}
8787
}
8888

89+
/// Serializes a json value into a io::writer
90+
fn to_writer_pretty(wr: io::Writer, j: Json, indent: uint) {
91+
fn spaces(n: uint) -> ~str {
92+
let ss = ~"";
93+
n.times { str::push_str(ss, " "); }
94+
return ss;
95+
}
96+
97+
match j {
98+
Num(n) => wr.write_str(float::to_str(n, 6u)),
99+
String(s) => wr.write_str(escape_str(*s)),
100+
Boolean(b) => wr.write_str(if b { ~"true" } else { ~"false" }),
101+
List(v) => {
102+
// [
103+
wr.write_str(spaces(indent));
104+
wr.write_str("[ ");
105+
106+
// [ elem,
107+
// elem,
108+
// elem ]
109+
let inner_indent = indent + 2;
110+
let mut first = true;
111+
for (*v).each |item| {
112+
if !first {
113+
wr.write_str(~",\n");
114+
wr.write_str(spaces(inner_indent));
115+
}
116+
first = false;
117+
to_writer_pretty(wr, item, inner_indent);
118+
};
119+
120+
// ]
121+
wr.write_str(~" ]");
122+
}
123+
Dict(d) => {
124+
// {
125+
wr.write_str(spaces(indent));
126+
wr.write_str(~"{ ");
127+
128+
// { k: v,
129+
// k: v,
130+
// k: v }
131+
let inner_indent = indent + 2;
132+
let mut first = true;
133+
for d.each |key, value| {
134+
if !first {
135+
wr.write_str(~",\n");
136+
wr.write_str(spaces(inner_indent));
137+
}
138+
first = false;
139+
let key = str::append(escape_str(key), ~": ");
140+
let key_indent = str::len(key);
141+
wr.write_str(key);
142+
to_writer_pretty(wr, value, key_indent);
143+
};
144+
145+
// }
146+
wr.write_str(~" }");
147+
}
148+
Null => wr.write_str(~"null")
149+
}
150+
}
151+
89152
fn escape_str(s: ~str) -> ~str {
90153
let mut escaped = ~"\"";
91154
do str::chars_iter(s) |c| {
@@ -111,6 +174,11 @@ fn to_str(j: Json) -> ~str {
111174
io::with_str_writer(|wr| to_writer(wr, j))
112175
}
113176

177+
/// Serializes a json value into a string, with whitespace and sorting
178+
fn to_str_pretty(j: Json) -> ~str {
179+
io::with_str_writer(|wr| to_writer_pretty(wr, j, 0))
180+
}
181+
114182
type Parser_ = {
115183
rdr: io::Reader,
116184
mut ch: char,

0 commit comments

Comments
 (0)