Search code examples
c++rapidjson

Print JSON with matching key - RapidJSON


I'm trying to print from a JSON only the values that matching some keys:

#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>

using namespace rapidjson;

char* kTypeNames[] = { "First", "text", "print", "key" };

int main() {
// 1. Parse a JSON string into DOM.
const char json[] =
" { \"First\" : \"a\", \"text\" : \"b\" ,\"key\" : \"hello\" ,
\"print\" : \"1\",\"print\" : \"2\",\"no_key\" : \"2\"} ";
// ...
Document document;
document.Parse(json);

printf(json);

printf("\nAccess values in document:\n");
assert(document.IsObject());

for (Value::ConstMemberIterator itr = document.MemberBegin();
itr !=document.MemberEnd(); ++itr)
{
    //how to print element that matches with kTypeNames array?
}
}

Keys needed are First, text, print and key, and I want to ignore no_key value. So I want to print only a, b, hello, 1 and do not print 2.

I'm looking and the documentation trying to find out how to do it.

Thanks


Solution

  • You don't need to iterate each member and see if it matches in the 'key' list. Rather use document.HasMember() to see if the key exists.

    #include "rapidjson/document.h"
    #include "rapidjson/writer.h"
    #include "rapidjson/stringbuffer.h"
    #include <iostream>
    
    using namespace rapidjson;
    
    const char* kTypeNames[] = { "First", "text", "print", "key" };
    
    int main() {
        // 1. Parse a JSON string into DOM.
        const char json[] =
            " { \"First\" : \"a\", \"text\" : \"b\" ,\"key\" : \"hello\" ,\"print\" : \"1\",\"print\" : \"2\",\"no_key\" : \"2\"} ";
        // ...
        Document document;
        document.Parse(json);
    
        printf(json);
    
        printf("\nAccess values in document:\n");
        assert(document.IsObject());
    
      //For each type in ktypenames, see if json has member
    
        for (auto Typename : kTypeNames) {
            if (document.HasMember(Typename)) {
                std::cout << Typename << ":" << document[Typename].GetString() << std::endl;
            }
    
        }
    }