Using JSON in Modern C++

Creating a JSON object from a file

How can I create a JSON object by reading the contents of a JSON file?

Abstract art representing computer programming

To create a JSON object from the contents of a JSON file, you can use the json::parse method in combination with a file stream:

#include <iostream>
#include <fstream>
#include <json.hpp>
using json = nlohmann::json;

int main() {
  std::ifstream file("data.json");
  json data = json::parse(file);

  std::cout << data.dump(2);

This code opens the file "data.json" for reading using an std::ifstream. It then passes the file stream directly to json::parse, which will read the file contents and parse it into a json object.

We can then access the data from the JSON object as normal, such as outputting it to the console using dump().

Make sure to #include <fstream> to bring in the file stream functionality.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved