dropbox / json11

A tiny JSON library for C++11.
MIT License
2.55k stars 613 forks source link

How to create json object of different types of values and containers all together ? #85

Closed Shravan40 closed 7 years ago

Shravan40 commented 7 years ago

I have some values of type int, double and string type. Along with them i have one 1-1 std::vector of 1-D and 2-D respectively.

How to build json object of such types.

I have tried this but i don't why, it didn't work.

Json my_json = Json::object {
    { "key1", intVal },
    { "key2", doubleVal },
    { "key3", "stringVal"},
    { "key4", Json::array (vector1d) }, // Not sure of this part.
    {"key5", Json::array (vector2d)}, // Not sure of this part too.
};
artwyman commented 7 years ago

If I'm guessing the right types for your variables, I believe if you change the parens to braces on the two instances of Json::array it'll compile.

Shravan40 commented 7 years ago

It did compile, but final outcome is bit strange. I want outcome to be

{
    "Key3":[["string1","string2"]], 
    "Key1": 200000,
    "key2": 150.55,
   //and so on..
}

But i think value corresponding to key3 should be ["string1","string2"] instead of [["string1","string2"]]

artwyman commented 7 years ago

Oh, you're looking for an array-of-array, with a single value? That's sadly a quirk of the language standard which got broken a couple years ago. When you construct a Json11::array from another Json11::array it's being interpreted as a move or copy, rather than creating another layer. That used to work until a related language specification tweak broke it. We've pushed the standards committee to reconsider, and they're tracking it as an issue, but I haven't seen any action. The new issue is listed here: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2137

There's a "canary" in the utests which is meant to point out if your compiler has the dangerous version, which you can see here: https://github.com/dropbox/json11/blob/master/test.cpp#L195

Most compilers are the dangerous version now, though, since it's the stated standard. Meanwhile, if you want those nested arrays, you'll need to build them in multiple steps using push_back.

Shravan40 commented 7 years ago

@artwyman : thanks :)

But i wanted something like this

Json my_json = Json::object {
    { "key1", intVal },
    { "key2", doubleVal },
    { "key3", "stringVal"},
    { "key4", vector1d },
    {"key5", vector2d},
};