Created
October 22, 2018 15:41
-
-
Save tanishiking/a453fbaca2bb0b6d0c32e03fe80dca1b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io" | |
"fmt" | |
"bufio" | |
"os" | |
"flag" | |
"github.com/tidwall/gjson" | |
p "github.com/tanishiking/prettier" | |
) | |
func main() { | |
var ( | |
width int | |
) | |
flag.IntVar(&width, "w", 80, "width") | |
flag.Parse() | |
reader := bufio.NewReader(os.Stdin) | |
var output []rune | |
for { | |
input, _, err := reader.ReadRune() | |
if err != nil && err == io.EOF { | |
break | |
} | |
output = append(output, input) | |
} | |
json := string(output) | |
if (!gjson.Valid(json)) { | |
panic("error") | |
} | |
result := gjson.Parse(json) | |
doc := gjsonResultToDoc(result) | |
// fmt.Println(doc.String()) | |
fmt.Println(p.Pretty(width, doc)) | |
} | |
func gjsonResultToDoc(r gjson.Result) p.Doc { | |
switch r.Type { | |
default: | |
return p.Empty() | |
case gjson.Null: | |
return p.Text("null") | |
case gjson.False: | |
return p.Text("false") | |
case gjson.Number: | |
return p.Text(fmt.Sprintf("%v", r.Num)) | |
case gjson.String: | |
return p.Text(fmt.Sprintf("\"%v\"", r.Str)) | |
case gjson.True: | |
return p.Text("true") | |
case gjson.JSON: | |
if (r.IsArray()) { | |
rs := r.Array() | |
ds := make([]p.Doc, len(rs)) | |
comma := p.Text(",") | |
for i, r := range rs { | |
ds[i] = p.Group(p.Concat([]p.Doc{p.Line(), gjsonResultToDoc(r)})) | |
} | |
parts := p.Intercalate(comma, ds) | |
return p.Concat([]p.Doc{ | |
p.Text("["), | |
p.Nest(uint(2), p.Concat([]p.Doc{parts, p.Text("]")})), | |
}) | |
} else { | |
var kvs []p.Doc | |
r.ForEach(func (k gjson.Result, v gjson.Result) bool { | |
value := gjsonResultToDoc(v) | |
kv := p.Concat([]p.Doc{ | |
p.Text(k.Str), | |
p.Text(":"), | |
p.Nest(uint(2), p.Concat([]p.Doc{p.LineOrSpace(), value})), | |
}) | |
kvs = append(kvs, kv) | |
return true | |
}) | |
parts := p.Fill(p.Text(","), kvs) | |
return p.TightBracketBy( | |
p.Text("{"), | |
p.Text("}"), | |
parts, | |
uint(2), | |
) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment