cheshire icon indicating copy to clipboard operation
cheshire copied to clipboard

Encoding infinity or NaN will decode to String

Open ABeltramo opened this issue 6 years ago • 2 comments

Encoding Double "positive infinity" value will be decoded back as the string "infinity". Example:

(cheshire.core/encode Double/POSITIVE_INFINITY)
=> "\"Infinity\""
(-> (cheshire.core/encode Double/POSITIVE_INFINITY) (cheshire.core/decode))
=> "Infinity"
(-> (cheshire.core/encode Double/POSITIVE_INFINITY) (cheshire.core/decode) (type))
=> java.lang.String

Same issue with NaN values (related to #92?):

(cheshire.core/encode Double/NaN)
=> "\"NaN\""
(-> (cheshire.core/encode Double/NaN) (cheshire.core/decode))
=> "NaN"
(-> (cheshire.core/encode Double/NaN) (cheshire.core/decode) (type))
=> java.lang.String

There is a related issue on clojure/data.json.

ABeltramo avatar Sep 19 '19 10:09 ABeltramo

Hi @ABeltramo, Jackson supports an option to allow parsing Infinity back, you can set it with the :allow-non-numeric-numbers true option, here's an example from Cheshire's tests:

(deftest t-bindable-factories
  (binding [fact/*json-factory* (fact/make-json-factory
                                 {:allow-non-numeric-numbers true})]
    (is (= (type Double/NaN)
           (type (:foo (json/decode "{\"foo\":NaN}" true)))))))

However, this appears only to support parsing Infinity and NaN, not "Infinity" and "NaN", I'm not sure yet the best way to address this.

dakrone avatar Sep 19 '19 16:09 dakrone

Hi @dakrone, thanks for the getting back at me. Unfortunately that doesn't solve the issue:

(binding [cheshire.factory/*json-factory* (cheshire.factory/make-json-factory
                                            {:allow-non-numeric-numbers true})]
  (-> (json/encode Double/NaN)
      (json/decode)))
=> "NaN"

(binding [cheshire.factory/*json-factory* (cheshire.factory/make-json-factory
                                            {:allow-non-numeric-numbers true})]
  (-> (json/encode Double/NaN)
      (json/decode)
      (type)))
=> java.lang.String

Given that JSON doesn't support NaN or Infinite you should either throw an exception or put nil as the value, imho.

ABeltramo avatar Sep 20 '19 08:09 ABeltramo