iterJSONObjects 扫描 text 中所有花括号平衡的 JSON 对象。 按出现顺序返回(只对顶层对象计数,字符串里的 {} 不算)。
(text string)
| 100 | // iterJSONObjects 扫描 text 中所有花括号平衡的 JSON 对象。 |
| 101 | // 按出现顺序返回(只对顶层对象计数,字符串里的 {} 不算)。 |
| 102 | func iterJSONObjects(text string) []map[string]any { |
| 103 | var out []map[string]any |
| 104 | depth := 0 |
| 105 | inStr := false |
| 106 | esc := false |
| 107 | start := -1 |
| 108 | for i := 0; i < len(text); i++ { |
| 109 | c := text[i] |
| 110 | if esc { |
| 111 | esc = false |
| 112 | continue |
| 113 | } |
| 114 | if c == '\\' { |
| 115 | esc = true |
| 116 | continue |
| 117 | } |
| 118 | if c == '"' { |
| 119 | inStr = !inStr |
| 120 | continue |
| 121 | } |
| 122 | if inStr { |
| 123 | continue |
| 124 | } |
| 125 | switch c { |
| 126 | case '{': |
| 127 | if depth == 0 { |
| 128 | start = i |
| 129 | } |
| 130 | depth++ |
| 131 | case '}': |
| 132 | depth-- |
| 133 | if depth == 0 && start >= 0 { |
| 134 | blob := text[start : i+1] |
| 135 | if v, ok := robustJSON(blob); ok { |
| 136 | out = append(out, v) |
| 137 | } |
| 138 | start = -1 |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | return out |
| 143 | } |
| 144 | |
| 145 | // cmdToString 把 cmd 字段归一化成单行命令: |
| 146 | // - "ls -la" → "ls -la" |
no test coverage detected