Commit da7c2c0ee90104524ed98a2370af0ea70a0f6d0d

Authored by Jay Berkenbilt
1 parent d2260925

Fix json serialization for {x | -1 < x < 1} (fixes #308)

JSON serialization was preserving the value as presented, but JSON
doesn't accept decimal values without a 0 before the decimal point.
ChangeLog
  1 +2019-03-11 Jay Berkenbilt <ejb@ql.org>
  2 +
  3 + * JSON serialization: add missing leading 0 to decimal values
  4 + between -1 and 1. Fixes #308.
  5 +
1 2019-02-01 Jay Berkenbilt <ejb@ql.org> 6 2019-02-01 Jay Berkenbilt <ejb@ql.org>
2 7
3 * 8.4.0: release 8 * 8.4.0: release
libqpdf/QPDF_Real.cc
@@ -25,7 +25,30 @@ QPDF_Real::unparse() @@ -25,7 +25,30 @@ QPDF_Real::unparse()
25 JSON 25 JSON
26 QPDF_Real::getJSON() 26 QPDF_Real::getJSON()
27 { 27 {
28 - return JSON::makeNumber(this->val); 28 + // While PDF allows .x or -.x, JSON does not. Rather than
  29 + // convering from string to double and back, just handle this as a
  30 + // special case for JSON.
  31 + std::string result;
  32 + if (this->val.length() == 0)
  33 + {
  34 + // Can't really happen...
  35 + result = "0";
  36 + }
  37 + else if (this->val.at(0) == '.')
  38 + {
  39 + result = "0" + this->val;
  40 + }
  41 + else if ((this->val.length() >= 2) &&
  42 + (this->val.at(0) == '-') &&
  43 + (this->val.at(1) == '.'))
  44 + {
  45 + result = "-0." + this->val.substr(2);
  46 + }
  47 + else
  48 + {
  49 + result = this->val;
  50 + }
  51 + return JSON::makeNumber(result);
29 } 52 }
30 53
31 QPDFObject::object_type_e 54 QPDFObject::object_type_e
libtests/json.cc
@@ -3,7 +3,7 @@ @@ -3,7 +3,7 @@
3 #include <iostream> 3 #include <iostream>
4 #include <assert.h> 4 #include <assert.h>
5 5
6 -static void check(JSON& j, std::string const& exp) 6 +static void check(JSON const& j, std::string const& exp)
7 { 7 {
8 if (exp != j.unparse()) 8 if (exp != j.unparse())
9 { 9 {
@@ -69,6 +69,10 @@ static void test_main() @@ -69,6 +69,10 @@ static void test_main()
69 " ],\n" 69 " ],\n"
70 " \"yes\": false\n" 70 " \"yes\": false\n"
71 "}"); 71 "}");
  72 + check(QPDFObjectHandle::newReal("0.12").getJSON(), "0.12");
  73 + check(QPDFObjectHandle::newReal(".34").getJSON(), "0.34");
  74 + check(QPDFObjectHandle::newReal("-0.56").getJSON(), "-0.56");
  75 + check(QPDFObjectHandle::newReal("-.78").getJSON(), "-0.78");
72 } 76 }
73 77
74 static void check_schema(JSON& obj, JSON& schema, bool exp, 78 static void check_schema(JSON& obj, JSON& schema, bool exp,