Skip to content

Commit 0ffbc52

Browse files
committed
json: encoder now has pretty print options.
... with no way to configure them yet, admittedly. I don't want to further bifrucate the already alarming number of top-level methods there are for setting up your marshallers and unmarshallers. It's probably time to get a move-on on those options structs and actually make them do some work. ... oooh. And we can make those a lot less ugly now that golang has aliases. That'll let us put the configuration struct types in their relevant packages, and alias them out to the top level package with all its other convenience methods. Signed-off-by: Eric Myhre <hash@exultant.us>
1 parent e8b5eff commit 0ffbc52

1 file changed

Lines changed: 16 additions & 1 deletion

File tree

json/jsonEncoder.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,9 @@ func (d *Encoder) Reset() {
2525
A json.Encoder is a TokenSink implementation that emits json bytes.
2626
*/
2727
type Encoder struct {
28-
wr io.Writer
28+
wr io.Writer
29+
indent []byte
30+
line []byte
2931

3032
// Stack, tracking how many array and map opens are outstanding.
3133
// (Values are only 'phase_mapExpectKeyOrEnd' and 'phase_arrExpectValueOrEnd'.)
@@ -74,6 +76,10 @@ func (d *Encoder) Step(tok *Token) (done bool, err error) {
7476
case TArrOpen:
7577
return true, fmt.Errorf("unexpected arrOpen; expected start of key or end of map")
7678
case TMapClose:
79+
d.wr.Write(d.line)
80+
for i := 1; i < len(d.stack); i++ {
81+
d.wr.Write(d.indent)
82+
}
7783
d.wr.Write(wordMapClose)
7884
return d.popPhase()
7985
case TArrClose:
@@ -126,6 +132,10 @@ func (d *Encoder) Step(tok *Token) (done bool, err error) {
126132
case TMapClose:
127133
return true, fmt.Errorf("unexpected mapClose; expected start of value or end of array")
128134
case TArrClose:
135+
d.wr.Write(d.line)
136+
for i := 1; i < len(d.stack); i++ {
137+
d.wr.Write(d.indent)
138+
}
129139
d.wr.Write(wordArrClose)
130140
return d.popPhase()
131141
default:
@@ -149,6 +159,7 @@ func (d *Encoder) pushPhase(p phase) {
149159
func (d *Encoder) popPhase() (bool, error) {
150160
n := len(d.stack) - 1
151161
if n == 0 {
162+
d.wr.Write(d.line)
152163
return true, nil
153164
}
154165
if n < 0 { // the state machines are supposed to have already errored better
@@ -167,6 +178,10 @@ func (d *Encoder) entrySep() {
167178
d.wr.Write(wordComma)
168179
}
169180
d.some = true
181+
d.wr.Write(d.line)
182+
for i := 0; i < len(d.stack); i++ {
183+
d.wr.Write(d.indent)
184+
}
170185
}
171186

172187
func (d *Encoder) flushValue(tok *Token) {

0 commit comments

Comments
 (0)