Я пытаюсь распечатать из 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.
Я смотрю и документацию пытаюсь выяснить, как это сделать.
Спасибо
Вам не нужно повторять каждый член и смотреть, соответствует ли он в списке «ключей». Вместо этого используйте 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;
}
}
}