Skip to content

Instantly share code, notes, and snippets.

@scbizu
Created August 19, 2016 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scbizu/3a9b12a822a2563bc406f9aeaae48969 to your computer and use it in GitHub Desktop.
Save scbizu/3a9b12a822a2563bc406f9aeaae48969 to your computer and use it in GitHub Desktop.
golang json.Indent() 的一种实现
package jparse
import (
"bytes"
"encoding/json"
)
func newline(dst *bytes.Buffer, depth int) {
dst.WriteByte('\n')
dst.WriteString("")
for i := 0; i < depth; i++ {
dst.WriteString(" ")
}
}
func Beauty(dst *bytes.Buffer, src []byte) error {
var counts int = 0
var dstjson interface{}
var lastbyte byte
err := json.Unmarshal(src, &dstjson)
if err != nil {
return err
}
//flag ro Indent dft:false
Indentflag := false
quoteflag := true
// scanner.reset()
//json depth(line)
layerdep := 0
//traverse src
for _, v := range src {
if counts >= 1 {
lastbyte = src[counts-1]
}
// log.Println("v: ", string(v))
counts++
if Indentflag == true && quoteflag == true {
Indentflag = false
layerdep++
newline(dst, layerdep)
}
switch v {
case '[', '{':
if quoteflag {
Indentflag = true
}
dst.WriteByte(v)
case ',':
dst.WriteByte(v)
//keep the depth
newline(dst, layerdep)
case ':':
dst.WriteByte(v)
dst.WriteByte(' ')
//end a section or end the json shold back a '\t' or other format char
case ']', '}':
if quoteflag {
if Indentflag {
Indentflag = false
} else {
layerdep--
newline(dst, layerdep)
}
}
//in the end print
dst.WriteByte(v)
case '"':
//whether the string must have double quote?
if lastbyte != '\\' {
// log.Println("Last byte: ", string(lastbyte))
quoteflag = !quoteflag
}
dst.WriteByte(v)
default:
dst.WriteByte(v)
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment