|
363 | 363 | (throw (Exception. |
364 | 364 | (str "JSON error (unexpected character): " (char c)))))))) |
365 | 365 |
|
| 366 | +(defn- -read1 |
| 367 | + [^PushbackReader stream eof-error? eof-value options] |
| 368 | + (let [val (-read stream eof-error? eof-value options)] |
| 369 | + (if-let [extra-data-fn (:extra-data-fn options)] |
| 370 | + (if (or eof-error? (not (identical? eof-value val))) |
| 371 | + (let [c (.read stream)] |
| 372 | + (if (neg? c) |
| 373 | + val |
| 374 | + (do |
| 375 | + (.unread stream c) |
| 376 | + (extra-data-fn val stream)))) |
| 377 | + val) |
| 378 | + val))) |
| 379 | + |
| 380 | +(defn on-extra-throw |
| 381 | + "Pass as :extra-data-fn to `read` or `read-str` to throw if data is found |
| 382 | + after the first object." |
| 383 | + [val rdr] |
| 384 | + (throw (ex-info "Found extra data after json object" {:val val}))) |
| 385 | + |
| 386 | +(defn on-extra-throw-remaining |
| 387 | + "Pass as :extra-data-fn to `read` or `read-str` to throw if data is found |
| 388 | + after the first object and return the remaining data in ex-data :remaining." |
| 389 | + [val ^java.io.PushbackReader rdr] |
| 390 | + (let [remaining (slurp rdr)] |
| 391 | + (throw (ex-info (str "Found extra data after json object: " remaining) |
| 392 | + {:val val, :remaining remaining})))) |
| 393 | + |
366 | 394 | (def default-read-options {:bigdec false |
367 | 395 | :key-fn nil |
368 | 396 | :value-fn nil}) |
|
404 | 432 | in the output. If value-fn returns itself, the property will |
405 | 433 | be omitted from the output. The default value-fn returns the |
406 | 434 | value unchanged. This option does not apply to non-map |
407 | | - collections." |
| 435 | + collections. |
| 436 | +
|
| 437 | + :extra-data-fn function |
| 438 | +
|
| 439 | + If :extra-data-fn is not nil, then the reader will be checked |
| 440 | + for extra data after the read. If found, the extra-data-fn will |
| 441 | + be invoked with the read value and the reader. The result of |
| 442 | + the extra-data-fn will be returned." |
408 | 443 | [reader & {:as options}] |
409 | 444 | (let [{:keys [eof-error? eof-value] |
410 | 445 | :or {eof-error? true}} options |
|
413 | 448 | (PushbackReader. reader 64))] |
414 | 449 | (->> options |
415 | 450 | (merge default-read-options) |
416 | | - (-read pbr eof-error? eof-value)))) |
| 451 | + (-read1 pbr eof-error? eof-value)))) |
417 | 452 |
|
418 | 453 | (defn read-str |
419 | 454 | "Reads one JSON value from input String. Options are the same as for |
|
423 | 458 | :or {eof-error? true}} options] |
424 | 459 | (->> options |
425 | 460 | (merge default-read-options) |
426 | | - (-read (PushbackReader. (StringReader. string) 64) eof-error? eof-value)))) |
| 461 | + (-read1 (PushbackReader. (StringReader. string) 64) eof-error? eof-value)))) |
427 | 462 |
|
428 | 463 | ;;; JSON WRITER |
429 | 464 |
|
|
0 commit comments