json-read-with-error-context
Clojure
(require '[clojure.edn :as edn]
'[clojure.string :as str])
(defn parse-json
"Parses JSON into EDN and rethrows failures with the error and nearby text."
[s]
(try
(edn/read-string (str/replace s #"(?:\"(?:\\.|[^\"\\])*\")|null" #(if (= % "null") "nil" %)))
(catch Exception e
(let [trimmed (str/triml (str s))
near (subs trimmed 0 (min 40 (count trimmed)))]
(throw (ex-info (str "Invalid JSON near " (pr-str near) ": " (ex-message e))
{:near near} e))))))