Last active
May 24, 2022 18:43
-
-
Save llimllib/3fc3a8642f793f521044406f23cf94a8 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
$ echo '{"a":{"b":"quoted \" } {{{"}}{"c":{"d":2}}{"e":{"f":3}}' | go run firstobject.go | |
{"a":{"b":"quoted \" } {{{"}} |
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 ( | |
"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