Categories

See More
Popular Forum

MBA (4887) B.Tech (1769) Engineering (1486) Class 12 (1030) Study Abroad (1004) Computer Science and Engineering (988) Business Management Studies (865) BBA (846) Diploma (746) CAT (651) B.Com (648) B.Sc (643) JEE Mains (618) Mechanical Engineering (574) Exam (525) India (462) Career (452) All Time Q&A (439) Mass Communication (427) BCA (417) Science (384) Computers & IT (Non-Engg) (383) Medicine & Health Sciences (381) Hotel Management (373) Civil Engineering (353) MCA (349) Tuteehub Top Questions (348) Distance (340) Colleges in India (334)
See More

Find all keys JSON - RapidJSON

General Tech Bugs & Fixes
Max. 2000 characters
Replies

usr_profile.png
Brian Burl

User

( 7 months ago )

 

I need to find all the keys in the kTypeNames[] with rapidJSON library. Trying to iterate all the nodes but I'm missing something; here's the code:

#include <iostream>
#include <fstream>
#include <string>
#include <bits/stdc++.h>
#include <unistd.h>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"

using namespace rapidjson;

using namespace std;

const char* kTypeNames[] = { "id", "text", "templ_text", "key" };

int main(int argc, char* argv[]) {

string line;
char json[65000];
std::ifstream file(argv[1]);
unsigned long i = 0;
if (file.is_open()) {
    while (!file.eof()) {
        file.get(json[i]);
        i++;
    }
    file.close();
} else {
    cout << "Unable to open file";
}

Document document;
document.Parse(json);
printf("\n\n\n\n*********Access values in document**********\n");

assert(document.IsObject());

for (auto Typename : kTypeNames) {
    if (document.HasMember(Typename)) {

        cout << "\n";
        cout << Typename << ":" << document[Typename].GetString()<< endl;
        cout << "\n";
    }
    else {
        cout << "\n None\n";
    }
 }

It does not works with a nested JSON.

{
"node": {
    "text": "find this",
    "templ_text": "don't find",
    "ver": "don't find"
},
"ic": "",
"text": "also this",
"templ_text": "don't care",
"par": {
    "SET": {
        "vis": "<blabla>",
        "text": "keyFound",
        "templ_text": "don't need this"
    }

								 								 
							usr_profile.png
							
Rahul Chaudhary

User

( 7 months ago )

void parse(rapidjson::Value & value)
{
    for(auto Typename : kTypeNames)
    {
        if(value.HasMember(Typename))
        {
            if(value[Typename].IsString())
            {
                std::cout << Typename << ": " << value[Typename].GetString() << std::endl;
            }
        }
    }

    for(auto member = value.MemberBegin(); member != value.MemberEnd(); ++member)
    {
        if(member->value.IsObject())
        {
            parse(member->value);
        }
    }
}

what's your interest