Skip to content

Inconsistent behavior in conversion to array type #473

Closed
@nlohmann

Description

The library supports the conversion from JSON arrays to STL containers such as std::vector, std::list, etc. Example code would be:

json j = {1, 2, 3, 4};
std::vector<int> v = j;
std::list<int> l = j;
std:: forward_list <int> f = j;

However, the library's behavior is inconsistent when it comes to non-array values:

json j = 12;
std::vector<int> v = j; // throws std::domain_error: type must be array, but is number
std::list<int> l = j; // successfully creates list { 12 };
std::forward_list<int> f = j; // successfully creates list { 12 };

This inconsistent behavior is bad design. There are two possibilities to fix it:

  1. Always insist that the JSON value must be an array when a conversion to an STL container of list type is requested. This would mean the second example would produce an exception in all cases.
  2. Always create a result, even if it is singleton (in case for booleans, strings, and numbers) or even empty (in case of null).

Internally, we need to iterate over the array in most cases anyway, so we would have no extra costs for solution 2 irregardless of the type. That means: removing the test for an array type would not mean additional costs.

Any thoughts on this?

Metadata

Assignees

Labels

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions