Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Encoding infinity or NaN will decode to String #152

Open
ABeltramo opened this issue Sep 19, 2019 · 2 comments
Open

Encoding infinity or NaN will decode to String #152

ABeltramo opened this issue Sep 19, 2019 · 2 comments

Comments

@ABeltramo
Copy link

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.

@dakrone
Copy link
Owner

dakrone commented Sep 19, 2019

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.

@ABeltramo
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants