ForEach iterates through values. If the result represents a non-existent value, then no values will be iterated. If the result is an Object, the iterator will pass the key and value of each item. If the result is an Array, the iterator will only pass the value of each item. If the result is not a JS
(iterator func(key, value Result) bool)
| 232 | // the value of each item. If the result is not a JSON array or object, the |
| 233 | // iterator will pass back one value equal to the result. |
| 234 | func (t Result) ForEach(iterator func(key, value Result) bool) { |
| 235 | if !t.Exists() { |
| 236 | return |
| 237 | } |
| 238 | if t.Type != JSON { |
| 239 | iterator(Result{}, t) |
| 240 | return |
| 241 | } |
| 242 | json := t.Raw |
| 243 | var obj bool |
| 244 | var i int |
| 245 | var key, value Result |
| 246 | for ; i < len(json); i++ { |
| 247 | if json[i] == '{' { |
| 248 | i++ |
| 249 | key.Type = String |
| 250 | obj = true |
| 251 | break |
| 252 | } else if json[i] == '[' { |
| 253 | i++ |
| 254 | key.Type = Number |
| 255 | key.Num = -1 |
| 256 | break |
| 257 | } |
| 258 | if json[i] > ' ' { |
| 259 | return |
| 260 | } |
| 261 | } |
| 262 | var str string |
| 263 | var vesc bool |
| 264 | var ok bool |
| 265 | var idx int |
| 266 | for ; i < len(json); i++ { |
| 267 | if obj { |
| 268 | if json[i] != '"' { |
| 269 | continue |
| 270 | } |
| 271 | s := i |
| 272 | i, str, vesc, ok = parseString(json, i+1) |
| 273 | if !ok { |
| 274 | return |
| 275 | } |
| 276 | if vesc { |
| 277 | key.Str = unescape(str[1 : len(str)-1]) |
| 278 | } else { |
| 279 | key.Str = str[1 : len(str)-1] |
| 280 | } |
| 281 | key.Raw = str |
| 282 | key.Index = s + t.Index |
| 283 | } else { |
| 284 | key.Num += 1 |
| 285 | } |
| 286 | for ; i < len(json); i++ { |
| 287 | if json[i] <= ' ' || json[i] == ',' || json[i] == ':' { |
| 288 | continue |
| 289 | } |
| 290 | break |
| 291 | } |