Sai A Sai A
Updated date Dec 17, 2023
In this blog, we will learn how to convert JSON to a string in C++. Explore three methods, including library usage, manual conversion, and Boost.PropertyTree, with code examples and outputs.

Introduction:

In C++ programming, dealing with JSON data is a common task. JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write. However, in certain scenarios, it becomes necessary to convert JSON data into a string format within a C++ program. This blog explores various methods to achieve this conversion.

Method 1: Using a Library

One of the most simple ways to convert JSON to a string in C++ is by using a library. Libraries such as JSON for Modern C++ provide easy-to-use functions for handling JSON data. Let's look at a simple example:

#include <iostream>
#include <nlohmann/json.hpp>

int main() {
    // Create a JSON object
    nlohmann::json json_data = {
        {"name", "John Doe"},
        {"age", 30},
        {"city", "New York"}
    };

    // Convert JSON to string
    std::string json_string = json_data.dump();

    // Output the result
    std::cout << "Method 1 Output: " << json_string << std::endl;

    return 0;
}

Output:

Method 1 Output: {"age":30,"city":"New York","name":"John Doe"}

In this example, the nlohmann::json library is used to create a JSON object, and the dump() function is employed to convert it to a string.

Method 2: Manual Conversion

If you prefer not to use external libraries, you can manually convert JSON to a string in C++. This involves constructing the string by iterating through the JSON elements. Here's an illustration:

#include <iostream>
#include <sstream>

void jsonToString(const nlohmann::json& json_data, std::string& result) {
    std::ostringstream oss;
    oss << "{";

    // Iterate through JSON elements
    for (auto it = json_data.begin(); it != json_data.end(); ++it) {
        oss << "\"" << it.key() << "\":";

        // Check the type of the JSON value
        if (it.value().is_string()) {
            oss << "\"" << it.value().get<std::string>() << "\"";
        } else if (it.value().is_number()) {
            oss << it.value().get<int>();
        }

        // Add a comma if it's not the last element
        if (std::next(it) != json_data.end()) {
            oss << ",";
        }
    }

    oss << "}";
    result = oss.str();
}

int main() {
    // Create a JSON object
    nlohmann::json json_data = {
        {"name", "John Doe"},
        {"age", 30},
        {"city", "New York"}
    };

    // Convert JSON to string
    std::string json_string;
    jsonToString(json_data, json_string);

    // Output the result
    std::cout << "Method 2 Output: " << json_string << std::endl;

    return 0;
}

Output:

Method 2 Output: {"name":"John Doe","age":30,"city":"New York"}

This method involves explicitly constructing the string by iterating through the JSON elements, checking their types, and handling them accordingly.

Method 3: Boost.PropertyTree

Another method for JSON to string conversion involves using the Boost.PropertyTree library. This library provides a property tree data structure that can be used to represent and manipulate hierarchical data, including JSON-like structures.

#include <iostream>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>

int main() {
    // Create a property tree
    boost::property_tree::ptree pt;
    pt.put("name", "John Doe");
    pt.put("age", 30);
    pt.put("city", "New York");

    // Convert property tree to string
    std::ostringstream oss;
    boost::property_tree::json_parser::write_json(oss, pt);

    // Output the result
    std::cout << "Method 3 Output: " << oss.str() << std::endl;

    return 0;
}

Output:

Method 3 Output: {"age":30,"city":"New York","name":"John Doe"}

In this example, a property tree is created using Boost.PropertyTree, and the write_json function is used to convert it to a string.

Conclusion:

In conclusion, there are multiple ways to convert JSON to a string in C++, each with its advantages and use cases. Using a library like JSON for Modern C++ provides a convenient and readable solution, while manual conversion allows for more fine-grained control over the process. The Boost.PropertyTree library is also a capable option for those already familiar with Boost.

Comments (0)

There are no comments. Be the first to comment!!!