我正在尝试从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?
}
}
需要的键是首先是文本,打印和键,我想忽略no_key值。 所以我只想打印a,b,你好1,而不打印2。
我正在寻找文档,试图找出方法。
谢谢
答案 0 :(得分:0)
您不需要迭代每个成员,也不必在“密钥”列表中查看它是否匹配。宁可使用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;
}
}
}