Commit 4e76021c authored by Kenton Varda's avatar Kenton Varda

Merge pull request #308 from katreniak/bka-jsonInfNanAsString

Bka json inf nan as string
parents d5e04e32 b4c8f8cd
......@@ -129,8 +129,8 @@ const char ALL_TYPES_JSON[] =
" \"uInt16List\": [33333, 44444],\n"
" \"uInt32List\": [3333333333],\n"
" \"uInt64List\": [\"11111111111111111111\"],\n"
" \"float32List\": [5555.5, null, null, null],\n"
" \"float64List\": [7777.75, null, null, null],\n"
" \"float32List\": [5555.5, \"Infinity\", \"-Infinity\", \"NaN\"],\n"
" \"float64List\": [7777.75, \"Infinity\", \"-Infinity\", \"NaN\"],\n"
" \"textList\": [\"plugh\", \"xyzzy\", \"thud\"],\n"
" \"dataList\": [[111, 111, 112, 115], [101, 120, 104, 97, 117, 115, 116, 101, 100], [114, 102, 99, 51, 48, 57, 50]],\n"
" \"structList\": [\n"
......@@ -323,22 +323,6 @@ KJ_TEST("decode test message") {
auto decodedRoot = decodedMessage.initRoot<TestAllTypes>();
json.decode(encoded, decodedRoot);
// json encode serializes nan, inf and -inf as null.
auto float32List = decodedRoot.getFloat32List();
auto float64List = decodedRoot.getFloat64List();
KJ_EXPECT(kj::isNaN(float32List[1]));
KJ_EXPECT(kj::isNaN(float32List[2]));
KJ_EXPECT(kj::isNaN(float32List[3]));
KJ_EXPECT(kj::isNaN(float64List[1]));
KJ_EXPECT(kj::isNaN(float64List[2]));
KJ_EXPECT(kj::isNaN(float64List[3]));
float32List.set(1, kj::inf());
float32List.set(2, -kj::inf());
float32List.set(3, kj::nan());
float64List.set(1, kj::inf());
float64List.set(2, -kj::inf());
float64List.set(3, kj::nan());
KJ_EXPECT(root.toString().flatten() == decodedRoot.toString().flatten());
}
......
......@@ -250,10 +250,13 @@ void JsonCodec::encode(DynamicValue::Reader input, Type type, JsonValue::Builder
case schema::Type::FLOAT64:
{
double value = input.as<double>();
if (kj::inf() == value || -kj::inf() == value || kj::isNaN(value)) {
// These values are not allowed in the JSON spec. Setting the field as null matches the
// behavior of JSON.stringify in Firefox and Chrome.
output.setNull();
// Inf, -inf and NaN are not allowed in the JSON spec. Storing into string.
if (kj::inf() == value) {
output.setString("Infinity");
} else if (-kj::inf() == value) {
output.setString("-Infinity");
} else if (kj::isNaN(value)) {
output.setString("NaN");
} else {
output.setNumber(value);
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment