Skip to content

Instantly share code, notes, and snippets.

@scbizu scbizu/jparse.go
Created Aug 19, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.