1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
use test;
use json;
test ValueCreation {
JsonValue array;
array << 10 << "a" << 4.5;
check array.toS(0) == "[10,\"a\",4.5]";
JsonValue object;
object["a"] = 10;
object["b"] = 4.5;
object["c"] = false;
object["d"] = array;
check object.toS(0, true) == "{\"a\":10,\"b\":4.5,\"c\":false,\"d\":[10,\"a\",4.5]}";
}
test CustomSyntax {
Str ext = "10";
Int v = 8;
JsonValue j = 20;
var literal = json{
a: "b",
b: v + 1,
c: [ext, 3, 1.1],
d: j,
};
JsonValue manual;
manual["a"] = "b";
manual["b"] = v + 1;
manual["c"] = JsonValue(JsonValue:[ext, 3, 1.1]);
manual["d"] = j;
check literal == manual;
}
test Serialization {
JsonValue array;
array << 10 << "a" << 4.5;
JsonValue object;
object["a"] = 10;
object["b"] = 4.5;
object["c"] = false;
object["d"] = true;
object["e"] = array;
Str serialized = object.toS(0);
JsonValue roundtrip = parseJson(serialized);
check roundtrip["a"] == 10;
check roundtrip["b"] == 4.5;
check roundtrip["c"] == false;
check roundtrip["d"] == true;
JsonValue rArray = roundtrip["e"];
check rArray[0] == 10;
check rArray[1] == "a";
check rArray[2] == 4.5;
check roundtrip == object;
// This is mostly for safety.
check roundtrip.toS(0, true) == "{\"a\":10,\"b\":4.5,\"c\":false,\"d\":true,\"e\":[10,\"a\",4.5]}";
// Check so that binary parsing also works.
check parseJson(core:io:toUtf8(serialized)) == object;
// Check so that we throw on extra garbage.
// TODO: In the future, we should probably provide a "parse prefix" function.
check parseJson(serialized + "a") throws JsonParseError;
check parseJson(" " + serialized + " ") == object;
}
test StringEncoding {
JsonValue obj;
obj["well-known"] = "a\n\r\t";
obj["single"] = "aåäö";
obj["double"] = "heart:🤍";
Str serialized = obj.toS(0);
JsonValue copy = parseJson(serialized);
check obj == copy;
copy = parseJson(core:io:toUtf8(serialized));
check obj == copy;
}
|