Merge pull request #400 from totalgee/to_json_fixes

In to_json(), maintain the "type" of empty maps and vectors
This commit is contained in:
Jason Turner 2018-02-02 21:33:11 -07:00 committed by GitHub
commit bbaa6ed76f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 3 deletions

View File

@ -80,7 +80,7 @@ namespace chaiscript
try { try {
const std::map<std::string, Boxed_Value> m = chaiscript::boxed_cast<const std::map<std::string, Boxed_Value> &>(t_bv); const std::map<std::string, Boxed_Value> m = chaiscript::boxed_cast<const std::map<std::string, Boxed_Value> &>(t_bv);
json::JSON obj; json::JSON obj(json::JSON::Class::Object);
for (const auto &o : m) for (const auto &o : m)
{ {
obj[o.first] = to_json_object(o.second); obj[o.first] = to_json_object(o.second);
@ -93,7 +93,7 @@ namespace chaiscript
try { try {
const std::vector<Boxed_Value> v = chaiscript::boxed_cast<const std::vector<Boxed_Value> &>(t_bv); const std::vector<Boxed_Value> v = chaiscript::boxed_cast<const std::vector<Boxed_Value> &>(t_bv);
json::JSON obj; json::JSON obj(json::JSON::Class::Array);
for (size_t i = 0; i < v.size(); ++i) for (size_t i = 0; i < v.size(); ++i)
{ {
obj[i] = to_json_object(v[i]); obj[i] = to_json_object(v[i]);
@ -132,7 +132,7 @@ namespace chaiscript
try { try {
const chaiscript::dispatch::Dynamic_Object &o = boxed_cast<const dispatch::Dynamic_Object &>(t_bv); const chaiscript::dispatch::Dynamic_Object &o = boxed_cast<const dispatch::Dynamic_Object &>(t_bv);
json::JSON obj; json::JSON obj(json::JSON::Class::Object);
for (const auto &attr : o.get_attrs()) for (const auto &attr : o.get_attrs())
{ {
obj[attr.first] = to_json_object(attr.second); obj[attr.first] = to_json_object(attr.second);

18
unittests/json_15.chai Normal file
View File

@ -0,0 +1,18 @@
// Various to_json() tests
assert_equal(to_json(-13570), "-13570")
assert_equal(to_json(0.654321), "0.654321")
assert_equal(to_json("ChaiScript"), "\"ChaiScript\"")
assert_equal(to_json(true), "true")
assert_equal(to_json([1, 2, 3]), "[1, 2, 3]")
assert_equal(to_json(Vector()), "[]") // empty vector
assert_equal(to_json([]), "[]") // empty vector
assert_equal(to_json(Map()), "{\n\n}") // empty map
assert_equal(to_json(Dynamic_Object()), "{\n\n}") // empty object
// Round-trip JSON tests
assert_equal(from_json(to_json([])), [])
assert_equal(from_json(to_json(Map())), Map())
assert_equal(to_json(from_json("null")), "null")
assert_equal(from_json(to_json(["a": 5, "b": "stuff"])), ["a": 5, "b": "stuff"])
auto x = [3.5, true, false, "test", [], Vector(), Map()]
assert_equal(from_json(to_json(x)), x)