How create an array using libjson?

5.6k views Asked by At

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.)

1

There are 1 answers

2
Justin ᚅᚔᚈᚄᚒᚔ On BEST ANSWER

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.