Skip to content

Instantly share code, notes, and snippets.

@llimllib
Last active May 24, 2022 18:43
Show Gist options
  • Save llimllib/3fc3a8642f793f521044406f23cf94a8 to your computer and use it in GitHub Desktop.
Save llimllib/3fc3a8642f793f521044406f23cf94a8 to your computer and use it in GitHub Desktop.
$ echo '{"a":{"b":"quoted \" } {{{"}}{"c":{"d":2}}{"e":{"f":3}}' | go run firstobject.go
{"a":{"b":"quoted \" } {{{"}}
package main
import (
"bufio"
"io"
"os"
)
func main() {
r := bufio.NewReader(os.Stdin)
c, err := r.ReadByte()
if err != nil {
if err == io.EOF {
os.Stdout.WriteString("Empty input\n")
return
} else {
panic(err)
}
}
braces := 0
state := ""
out := make([]byte, 1024*1024) // set default bufsize to taste
for {
if state == "" && c == '{' {
braces += 1
} else if state == "" && c == '}' {
braces -= 1
if braces == 0 {
out = append(out, c)
break
}
} else if c == '"' {
if state == "QUOTED" {
state = ""
} else {
state = "QUOTED"
}
} else if state == "QUOTED" && c == '\\' {
state = "ESCAPE"
} else if state == "ESCAPE" {
state = "QUOTED"
}
out = append(out, c)
c, err = r.ReadByte()
if err != nil {
if err == io.EOF {
break
} else {
panic(err)
}
}
}
out = append(out, '\n')
os.Stdout.Write(out)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment