Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read/write JSON with c++?

Tags:

c++

json

I would like to know how to read/write a JSON file using C++. I will be using this file to store player info & setting for a simple game I'm making. It's nothing fancy, just a console number guessing game, but I just use it to learn stuff.

I have to know how to read & write specific parts of a JSON.

like image 899
Cubicalspy Avatar asked May 21 '26 01:05

Cubicalspy


1 Answers

Using a library, it can be done quite easily:

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

int main() {
    // read file
    auto json = nlohmann::json::parse("{\"value1\": \"string\"}");

    // mutate the json
    json["value1"] = "new string";

    // write to a stream, or the same file
    std::cout << json; // print the json
}

C++ don't have the built-ins for dealing with json. You can implement your own json data structure, or use one available like nlohmann/json or simdjson

You could create your own parser using pure C++ with the standard library only, but I would advise against, unless it's for learning purpose.

like image 197
Guillaume Racicot Avatar answered May 23 '26 15:05

Guillaume Racicot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!