extractJSONSegment 尝试在文本中找到第一个配平的 JSON 对象/数组片段。
(text string)
| 66 | |
| 67 | // extractJSONSegment 尝试在文本中找到第一个配平的 JSON 对象/数组片段。 |
| 68 | func 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 校验顶层字段是否存在。 |
| 105 | func checkRequiredFields(data any, required []string) []string { |
no outgoing calls
no test coverage detected