github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/builtins/types/jsonconcat/parser.go (about) 1 package jsonconcat 2 3 import "fmt" 4 5 func parse(b []byte, callback func([]byte)) error { 6 var ( 7 brace, last int 8 quote, escape bool 9 open, close byte 10 ) 11 12 if len(b) == 0 { 13 return nil 14 } 15 16 switch b[0] { 17 case '{': 18 open, close = '{', '}' 19 case '[': 20 open, close = '[', ']' 21 default: 22 return fmt.Errorf("invalid first character '%s'. This doesn't appear to be valid JSON", string([]byte{b[0]})) 23 } 24 25 for i := range b { 26 if escape { 27 escape = false 28 continue 29 } 30 31 switch b[i] { 32 case '\\': 33 escape = !escape 34 35 case '"': 36 quote = !quote 37 38 case open: 39 brace++ 40 41 case close: 42 brace-- 43 if brace == 0 { 44 json := make([]byte, i-last+1) 45 copy(json, b[last:i+1]) 46 callback(json) 47 last = i + 1 48 } 49 } 50 } 51 52 if brace > 0 { 53 return fmt.Errorf("reached end of document with %d missing `%s`", brace, string([]byte{close})) 54 } 55 56 return nil 57 }