Распечатать JSON с соответствующим ключом - RapidJSON - PullRequest
0 голосов
/ 10 апреля 2019

Я пытаюсь напечатать из JSON только те значения, которые соответствуют некоторым ключам:

#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?
}
}

Необходимые ключи: First, text, print и key, и я хочу игнорировать значение no_key.Поэтому я хочу напечатать только a, b, hello, 1 и не печатать 2.

Я ищу и документацию, пытаясь выяснить, как это сделать.

Спасибо

1 Ответ

0 голосов
/ 10 апреля 2019

Вам не нужно повторять каждый элемент и смотреть, соответствует ли он в списке «ключей». Вместо этого используйте document.HasMember(), чтобы увидеть, существует ли ключ.

#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;
        }

    }
}
...