Example method using rapidjson to parse nested json

  • 2020-06-15 09:57:07
  • OfStack

Parse nested json using rapidjson

Look at string 1 of json: {"system":{"version":"v2.6.1", "name":"value"}}

Less nonsense, direct line code:


#include <iostream>
#include <stdio.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<sstream>
//  Please download the open source one yourself rapidjson
#include "rapidjson/prettywriter.h"
#include "rapidjson/rapidjson.h"
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "rapidjson/memorystream.h"
using namespace std;
using rapidjson::Document;
using rapidjson::StringBuffer;
using rapidjson::Writer;
using namespace rapidjson;
string getVersion(const string &jvStr)
{
 Document document;
 if (document.Parse(jvStr.c_str()).HasParseError() || !document.HasMember("system")) 
 {
 return "";
 }
 const rapidjson::Value &jvObject = document["system"];
 if(!jvObject.IsObject())
 {
 return "";
 }
 if(!jvObject.HasMember("version"))
 {
 return "";
 }
 const rapidjson::Value &jv = jvObject["version"];
 return jv.GetString();
}
int main(int argc, char *argv[])
{
 string s = "{\"system\":{\"version\":\"v2.6.1\", \"name\":\"value\"}}";
 cout << s << endl;
 cout << getVersion(s) << endl;
 return 0;
}

Results:

[

{"system":{"version":"v2.6.1", "name":"value"}}
v2.6.1

]

Now look at the string: {"system": "{\"version\":\"v2.6.1\", \"name\":\"value\"}"}

Go straight to the horse:


#include <iostream>
#include <stdio.h>
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<sstream>
//  Please download the open source one yourself rapidjson
#include "rapidjson/prettywriter.h"
#include "rapidjson/rapidjson.h"
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "rapidjson/memorystream.h"
using namespace std;
using rapidjson::Document;
using rapidjson::StringBuffer;
using rapidjson::Writer;
using namespace rapidjson;
string getStringFromJson(const string &jsStr, const string &strKey) 
{ 
  Document document; 
  if (document.Parse(jsStr.c_str()).HasParseError() || !document.HasMember(strKey.c_str()))  
  { 
    return ""; 
  } 
  const rapidjson::Value &jv = document[strKey.c_str()]; 
  return jv.GetString(); 
} 
int main(int argc, char *argv[])
{
 string s = "{\"system\": \"{\\\"version\\\":\\\"v2.6.1\\\", \\\"name\\\":\\\"value\\\"}\"}";
 cout << s << endl;
 string str = getStringFromJson(s, "system");
 cout << str << endl;
 cout << getStringFromJson(str, "version") << endl;
 return 0;
}

Results:

[

{"system": "{\"version\":\"v2.6.1\", \"name\":\"value\"}"}
{"version":"v2.6.1", "name":"value"}
v2.6.1

]

The second way, json string, looks disgusting.

In addition, once again, json is easy to parse, core dump, so be sure to make exception judgment, also pay attention to the type.

conclusion


Related articles: