MCPcopy Create free account
hub / github.com/astercloud/aster / extractJSONSegment

Function extractJSONSegment

pkg/structured/structured.go:68–102  ·  view source on GitHub ↗

extractJSONSegment 尝试在文本中找到第一个配平的 JSON 对象/数组片段。

(text string)

Source from the content-addressed store, hash-verified

66
67// extractJSONSegment 尝试在文本中找到第一个配平的 JSON 对象/数组片段。
68func extractJSONSegment(text string) (string, error) {
69 start := -1
70 var open, close rune
71
72 for i, r := range text {
73 if r == '{' || r == '[' {
74 start = i
75 if r == '{' {
76 open, close = '{', '}'
77 } else {
78 open, close = '[', ']'
79 }
80 break
81 }
82 }
83
84 if start == -1 {
85 return "", errors.New("no json object/array found")
86 }
87
88 depth := 0
89 for i, r := range text[start:] {
90 switch r {
91 case open:
92 depth++
93 case close:
94 depth--
95 if depth == 0 {
96 return strings.TrimSpace(text[start : start+i+1]), nil
97 }
98 }
99 }
100
101 return "", errors.New("unbalanced json brackets")
102}
103
104// checkRequiredFields 校验顶层字段是否存在。
105func checkRequiredFields(data any, required []string) []string {

Callers 4

ParseMethod · 0.85
ParseIntoMethod · 0.85
ExtractAndParseMethod · 0.85
ParseTypedFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected