Search code examples
c++arraysjsonlibjson

How create an array using libjson?


I want to make an array with libJSON's JSONNode. I've tried the following, but it doesn't work:

JSONNode array;
JSONNode foo("word", "foo");
JSONNode bar("word", "bar");
array.push_back(foo);
array.push_back(bar);

This results in:

{ 
    "word": "foo", 
    "word": "bar"
}

What I want is:

[
    {"word": "foo"},
    {"word": "bar"}
]

It's clear to me that I'm not specifying that I want an array. The thing is, I've searched the library and googled a bit, but I find no way to do this. Can anybody help me out with this?

(Sidenote: I wanted to add a "libjson" tag, but that doesn't exist yet, it seems.)


Solution

  • You need to specify that you're creating an array and complex nodes:

    JSONNode array(JSON_ARRAY);
    JSONNode foo(JSON_NODE);
    JSONNode bar(JSON_NODE);
    
    foo.push_back(JSONNode("word", "foo"));
    bar.push_back(JSONNode("word", "bar"));
    
    array.push_back(foo);
    array.push_back(bar);
    

    See the "Getting Started" documentation in libjson-VERSION.zip for some basic examples.

    Side note: I've personally found libjson to be annoying to work with, and the documentation is severely lacking. In my own projects, I use either JsonCpp or (more frequently) Jansson as my C/C++ JSON API. If you're not locked in to libjson, you might give them a try.