RapidJSON is a high-performance JSON library for C++. It provides a fast and easy-to-use interface for parsing and generating JSON. It is small but complete. It supports both SAX and DOM style API. Also, it is self-contained and header-only. It does not depend on external libraries such as BOOST. It even does not depend on STL. Here is an example of how to parse a JSON file using RapidJSON.
Example 1:
#include "rapidjson/document.h" #include "rapidjson/filereadstream.h" #include <cstdio> int main()
{ // Open the file
FILE * fp = fopen ( "test.json" , "rb" );
// Read the file into a buffer
char readBuffer[65536];
rapidjson::FileReadStream is(fp, readBuffer,
sizeof (readBuffer));
// Parse the JSON document
rapidjson::Document doc;
doc.ParseStream(is);
// Close the file
fclose (fp);
// Use the data in the document
// ...
return 0;
} |
This example reads the contents of a file called “test.json” into a buffer and then parses the JSON document using the ParseStream function. The parsed document is stored in a rapidjson::Document object, which provides access to the data in the JSON document. You can then access the data in the document using the various member functions of the rapidjson::Document class. For example, to access an object member, you can use the GetObject function, and to access an array member, you can use the GetArray function. You can also use the HasMember function to check if an object has a particular member, and the Size function to get the size of an array. Here is a more detailed example of how to parse a JSON file using RapidJSON, with explanations of each step:
Example 2:
#include "rapidjson/document.h" #include "rapidjson/filereadstream.h" #include <cstdio> #include <iostream> int main()
{ // Open the file
FILE * fp = fopen ( "test.json" , "rb" );
// Check if the file was opened successfully
if (!fp) {
std::cerr << "Error: unable to open file"
<< std::endl;
return 1;
}
// Read the file into a buffer
char readBuffer[65536];
rapidjson::FileReadStream is(fp, readBuffer,
sizeof (readBuffer));
// Parse the JSON document
rapidjson::Document doc;
doc.ParseStream(is);
// Check if the document is valid
if (doc.HasParseError()) {
std::cerr << "Error: failed to parse JSON document"
<< std::endl;
fclose (fp);
return 1;
}
// Close the file
fclose (fp);
// Access the data in the document
// Suppose the JSON document has the following
// structure:
// {
// "name": "John Smith",
// "age": 30,
// "city": "New York",
// "skills": ["programming", "guitar", "singing"]
// }
// Get the "name" member
if (doc.HasMember( "name" ) && doc[ "name" ].IsString()) {
std::string name = doc[ "name" ].GetString();
std::cout << "Name: " << name << std::endl;
}
// Get the "age" member
if (doc.HasMember( "age" ) && doc[ "age" ].IsInt()) {
int age = doc[ "age" ].GetInt();
std::cout << "Age: " << age << std::endl;
}
// Get the "city" member
if (doc.HasMember( "city" ) && doc[ "city" ].IsString()) {
std::string city = doc[ "city" ].GetString();
std::cout << "City: " << city << std::endl;
}
// Get the "skills" array
if (doc.HasMember( "skills" )
&& doc[ "skills" ].IsArray()) {
const rapidjson::Value& skills = doc[ "skills" ];
std::cout << "Skills: " ;
for (rapidjson::SizeType i = 0; i < skills.Size();
i++) {
if (skills[i].IsString()) {
std::string skill = skills[i].GetString();
std::cout << skill << " " ;
}
}
std::cout << std::endl;
}
return 0;
} |
Sample test.json:
Output:
Explanation of Example:
In this example, we first open the file “test.json” using the fopen function. Then, we read the contents of the file into a buffer using the rapidjson::FileReadStream class. Parsing a JSON document means converting a JSON-formatted string into a JSON object that can be accessed and manipulated in your program. RapidJSON provides several functions for parsing JSON, including:
- Parse: parses a JSON string
- ParseInsitu: parses a JSON string in-place (i.e., without making a copy of the string)
- ParseStream: parses a JSON document from an input stream
Once a JSON document has been parsed, you can access the data in the document using the various member functions of the rapidjson::Document class. For example:
- IsObject: returns true if the document is an object
- IsArray: returns true if the document is an array
- IsString: returns true if the document is a string
- IsNumber: returns true if the document is a number (integer or floating-point)
- IsBool: returns true if the document is a boolean value
- GetObject: returns the object at the specified path within the document
- GetArray: returns the array at the specified path within the document
- GetString: returns the string at the specified path within the document
- GetInt: returns the integer at the specified path within the document
- GetUint: returns the unsigned integer at the specified path within the document
- GetInt64: returns the 64-bit integer at the specified path within the document
- GetUint64: returns the 64-bit unsigned integer at the specified path within the document
- GetDouble: returns the double-precision floating-point number at the specified path within the document
- GetBool: returns the boolean value at the specified path within the document
Here is an example of how to access data in a JSON document using these functions:
Example 3:
#include "rapidjson/document.h" int main()
{ // Parse the JSON document
rapidjson::Document doc;
doc.Parse( "{\"name\":\"John\",\"age\":30,\"city\":"
"\"New York\"}" );
// Access the data in the document
if (doc.IsObject()) {
// Get the "name" member
if (doc.HasMember( "name" )
&& doc[ "name" ].IsString()) {
std::string name = doc[ "name" ].GetString();
std::cout << "Name: " << name << std::endl;
// Output:- Name: John
}
// Get the "age" member
if (doc.HasMember( "age" ) && doc[ "age" ].IsInt()) {
int age = doc[ "age" ].GetInt();
std::cout << "Age: " << age << std::endl;
// Output:- Age: 30
}
// Get the "city" member
if (doc.HasMember( "city" )
&& doc[ "city" ].IsString()) {
std::string city = doc[ "city" ].GetString();
std::cout << "City: " << city << std::endl;
// Output:- City: New York
}
}
return 0;
} |
Output:
This code parses the JSON document contained in the string literal “{\”name\”:\”John\”,\”age\”:30,\”city\”:\”New York\”}” using the Parse() method of the rapidjson::Document object. The document is then accessed and the values of the “name”, “age”, and “city” members are extracted and printed to the console.