22

I have the following code:

void MyClass::myMethod(Json::Value& jsonValue_ref)
{
    for (int i = 0; i <= m_stringList.size(); i++)
    {
        if (m_boolMarkerList[i])
        {
            jsonValue_ref.append(stringList[i]);
        }
    }
}

void MyClass::myOuterMethod()
{
    Json::Value jsonRoot;
    Json::Value jsonValue;
    
    myMethod(jsonValue);

    jsonRoot["somevalue"] = jsonValue;
    Json::StyledWriter writer;
    std::string out_string = writer.write(jsonRoot);
}
    

If all markers in m_boolMarkerList are false, the out_string is { "somevalue" : null }, but I want it to be an empty array: { "somevalue" : [ ] }

Does anybody know how to achieve this?

Thank you very much!

3 Answers 3

47

Here are two ways you can do it:

jsonRootValue["emptyArray"] = Json::Value(Json::arrayValue);
// or 
jsonRootValue["emptyArray"] = Json::arrayValue;
Sign up to request clarification or add additional context in comments.

2 Comments

why not just jsonRootValue["emptyArray"] = Json::arrayValue;
I think maybe when I posted this question - two years before your comment - that was just not possible.
9

You can do this by defining the Value object as an "Array object" (by default it makes it as an "object" object which is why your member becomes "null" when no assignment made, instead of [] )

So, switch this line:

 Json::Value jsonValue;
 myMethod(jsonValue);

with this:

Json::Value jsonValue(Json::arrayValue);
myMethod(jsonValue);

And voila! Note that you can change "arrayValue" to any type you want (object, string, array, int etc.) to make an object of that type. As I said before, the default one is "object".

2 Comments

Thank you Ahmet but this is exactly the same as user609441 already stated with a little more text.
Wanted to explain the reasons as well ^_^
5

OK I got it. It is a little bit annoying but it is quite easy after all. To create an empty json array with jsoncpp:

Json::Value jsonArray;
jsonArray.append(Json::Value::null);
jsonArray.clear();
jsonRootValue["emptyArray"] = jsonArray;

Output via writer will be:

{ "emptyArray" = [] }         

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.