1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
9 // Compact appends to dst the JSON-encoded src with
10 // insignificant space characters elided.
11 func Compact(dst *bytes.Buffer, src []byte) error {
16 for i, c := range src {
17 v := scan.step(&scan, int(c))
18 if v >= scanSkipSpace {
23 dst.Write(src[start:i])
28 if scan.eof() == scanError {
33 dst.Write(src[start:])
38 func newline(dst *bytes.Buffer, prefix, indent string, depth int) {
40 dst.WriteString(prefix)
41 for i := 0; i < depth; i++ {
42 dst.WriteString(indent)
46 // Indent appends to dst an indented form of the JSON-encoded src.
47 // Each element in a JSON object or array begins on a new,
48 // indented line beginning with prefix followed by one or more
49 // copies of indent according to the indentation nesting.
50 // The data appended to dst has no trailing newline, to make it easier
51 // to embed inside other formatted JSON data.
52 func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error {
58 for _, c := range src {
60 v := scan.step(&scan, int(c))
61 if v == scanSkipSpace {
67 if needIndent && v != scanEndObject && v != scanEndArray {
70 newline(dst, prefix, indent, depth)
73 // Emit semantically uninteresting bytes
74 // (in particular, punctuation in strings) unmodified.
75 if v == scanContinue {
80 // Add spacing around real punctuation.
83 // delay indent so that empty object and array are formatted as {} and [].
89 newline(dst, prefix, indent, depth)
97 // suppress indent in empty object/array
101 newline(dst, prefix, indent, depth)
109 if scan.eof() == scanError {
110 dst.Truncate(origLen)