isValidJSONNumber reports whether s is a valid JSON number literal. From https://golang.org/src/encoding/json/encode.go#L652 isValidNumber Copyright 2010 The Go Authors.
(s string)
| 282 | // From https://golang.org/src/encoding/json/encode.go#L652 isValidNumber |
| 283 | // Copyright 2010 The Go Authors. |
| 284 | func isValidJSONNumber(s string) bool { |
| 285 | // This function implements the JSON numbers grammar. |
| 286 | // See https://tools.ietf.org/html/rfc7159#section-6 |
| 287 | // and https://www.json.org/img/number.png |
| 288 | |
| 289 | if s == "" { |
| 290 | return false |
| 291 | } |
| 292 | |
| 293 | // Optional - |
| 294 | if s[0] == '-' { |
| 295 | s = s[1:] |
| 296 | if s == "" { |
| 297 | return false |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | // Digits |
| 302 | switch { |
| 303 | default: |
| 304 | return false |
| 305 | |
| 306 | case s[0] == '0': |
| 307 | s = s[1:] |
| 308 | |
| 309 | case '1' <= s[0] && s[0] <= '9': |
| 310 | s = s[1:] |
| 311 | for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { |
| 312 | s = s[1:] |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | // . followed by 1 or more digits. |
| 317 | if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' { |
| 318 | s = s[2:] |
| 319 | for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { |
| 320 | s = s[1:] |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | // e or E followed by an optional - or + and |
| 325 | // 1 or more digits. |
| 326 | if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') { |
| 327 | s = s[1:] |
| 328 | if s[0] == '+' || s[0] == '-' { |
| 329 | s = s[1:] |
| 330 | if s == "" { |
| 331 | return false |
| 332 | } |
| 333 | } |
| 334 | for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { |
| 335 | s = s[1:] |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | // Make sure we are at the end. |
| 340 | return s == "" |
| 341 | } |