In this post, we will see about JSON parser in C++.
There is no native support for JSON in C++. We can use a number of libraries that provide support for JSON in C++. We will use JsonCpp to parse JSON files in C++ which is very popular. It is an open source library and is widely used for parsing JSON files in C++. There are no limitations for using this library. It allows reading and updating the JSON values. It can be used for serialization and deserialization from strings and to strings.
Table of Contents
JSON Data example:
1 2 3 4 5 6 |
{ "Name" : "Java2Blog", "category": "Programming" } |
Simple JSON Parser in C++ using JsonCpp library
We will include the necessary header files to define the interface to JsonCpp. We can use Json::Reader
and Json::Writer
for reading and writing in JSON files. Json::reader
will read the JSON file and will return the value as Json::Value
. Parsing the JSON is very simple by using parse()
.
fstream() is used to get the file pointer in the variable file
. parse()
is used to get the data. Errors can be checked at the time of parsing. Data can be modified with the help of JsonCpp. In the end, we will make the changes in the original file. Output can also be stored in a new file.
item.json
“Category” : “Programming”,
“Date” : “1 January 2021”,
“Name” : “Java2Blog”
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <cstdlib> #include <string> #include <fstream> #include <iostream> #include <json\value.h> #include <json\json.h> using namespace std; int main() { Json::Reader reader; //for reading the data Json::Value newValue; //for modifying and storing new values Json::StyledStreamWriter writer; //for writing in json files ofstream newFile; //opening file using fstream ifstream file("items.json"); // check if there is any error is getting data from the json file if (!reader.parse(file, newValue)) { cout << reader.getFormattedErrorMessages(); exit(1); } //Updating the json data newValue["Category"] = "Technical"; //we can add new values as well newValue["first"] = "Shishank"; newValue["last"] = "Jain"; // make the changes in a new file/original file newFile.open("items.json"); writer.write(newFile, newValue); newFile.close(); return 0; } |
Output items.json
file
“Category” : “Technical”,
“Date” : “1 January 2021”,
“Name” : “Java2Blog”,
“first” : “Shishank”,
“last” : “Jain”
}
Conclusion
JsonCpp
is a powerful and extensively used library to deal with JSON objects in C++. It supports multiple built-in functions which can help in parsing JSON data faster and we can get more properties of the JSON data. In this article, we explained how to parse JSON data in C++.
That’s all about JSON parser in C++.
Happy Learning!!