Commit 1c2cc125 authored by Stephen McQuay's avatar Stephen McQuay Committed by Andrew Gerrand

encoding/json: add example for Indent, clarify the docs.

There was confusion in the behavior of json.Indent; This change
attempts to clarify the behavior by providing a bit more verbiage
to the documentation as well as provide an example function.

Fixes #7821.

LGTM=robert.hencke, adg
R=golang-codereviews, minux.ma, bradfitz, aram, robert.hencke, r, adg
CC=golang-codereviews
https://golang.org/cl/97840044
parent 51392939
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
package json_test package json_test
import ( import (
"bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
...@@ -127,3 +128,34 @@ func ExampleRawMessage() { ...@@ -127,3 +128,34 @@ func ExampleRawMessage() {
// YCbCr &{255 0 -10} // YCbCr &{255 0 -10}
// RGB &{98 218 255} // RGB &{98 218 255}
} }
func ExampleIndent() {
type Road struct {
Name string
Number int
}
roads := []Road{
{"Diamond Fork", 29},
{"Sheep Creek", 51},
}
b, err := json.Marshal(roads)
if err != nil {
log.Fatal(err)
}
var out bytes.Buffer
json.Indent(&out, b, "=", "\t")
out.WriteTo(os.Stdout)
// Output:
// [
// = {
// = "Name": "Diamond Fork",
// = "Number": 29
// = },
// = {
// = "Name": "Sheep Creek",
// = "Number": 51
// = }
// =]
}
...@@ -69,8 +69,9 @@ func newline(dst *bytes.Buffer, prefix, indent string, depth int) { ...@@ -69,8 +69,9 @@ func newline(dst *bytes.Buffer, prefix, indent string, depth int) {
// Each element in a JSON object or array begins on a new, // Each element in a JSON object or array begins on a new,
// indented line beginning with prefix followed by one or more // indented line beginning with prefix followed by one or more
// copies of indent according to the indentation nesting. // copies of indent according to the indentation nesting.
// The data appended to dst has no trailing newline, to make it easier // The data appended to dst does not begin with the prefix nor
// to embed inside other formatted JSON data. // any indentation, and has no trailing newline, to make it
// easier to embed inside other formatted JSON data.
func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error { func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error {
origLen := dst.Len() origLen := dst.Len()
var scan scanner var scan scanner
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment