raise error when parsing object with NaN or INF to JSON
authorYan Wu <yanvv@fb.com>
Wed, 5 Feb 2014 09:31:38 +0000 (01:31 -0800)
committerSara Golemon <sgolemon@fb.com>
Thu, 6 Feb 2014 19:50:14 +0000 (11:50 -0800)
Summary:
NaN or INF is not allowed according to JSON specification.
This will cause problems when other places try to encode the output
of toJson with NaN or INF.
raise error when parsing object with NaN or INF to JSON.

Test Plan: manually test, raise error for object w/ NaN

Reviewed By: delong.j@fb.com

FB internal diff: D1143853

folly/json.cpp
folly/json.h

index f248ef8e324a416af14a973b7636c1c6cfd80948..28fe5f11e992806f3949d6b42a32d26c66894b74 100644 (file)
@@ -126,6 +126,11 @@ struct Printer {
   void operator()(dynamic const& v) const {
     switch (v.type()) {
     case dynamic::DOUBLE:
+      if (!opts_.allow_nan_inf &&
+          (isnan(v.asDouble()) || isinf(v.asDouble()))) {
+        throw std::runtime_error("folly::toJson: JSON object value was a "
+          "NaN or INF");
+      }
       toAppend(v.asDouble(), &out_);
       break;
     case dynamic::INT64: {
@@ -751,6 +756,7 @@ fbstring toPrettyJson(dynamic const& dyn) {
 void dynamic::print_as_pseudo_json(std::ostream& out) const {
   json::serialization_opts opts;
   opts.allow_non_string_keys = true;
+  opts.allow_nan_inf = true;
   out << json::serialize(*this, opts);
 }
 
index 527eb235a765d2ba71a5ae509db835a8a2bed134..8b5ce55a2f4e26d6df87b9e9a485399a32decfa4 100644 (file)
@@ -61,6 +61,7 @@ namespace json {
       , allow_trailing_comma(false)
       , sort_keys(false)
       , skip_invalid_utf8(false)
+      , allow_nan_inf(false)
     {}
 
     // If true, keys in an object can be non-strings.  (In strict
@@ -93,6 +94,9 @@ namespace json {
 
     // Replace invalid utf8 characters with U+FFFD and continue
     bool skip_invalid_utf8;
+
+    // true to allow NaN or INF values
+    bool allow_nan_inf;
   };
 
   /*