如何使用 C++ 读取和使用 JSON 文件中的数据

Cav*_*lan 2 c++ json

我希望读取 JSON 文件并使用该信息来创建多项选择测验。我只是无法理解如何从 JSON 文件中实际读取它。我已经设法读对了问题的数量,但仅此而已。

这是我的 JSON 文件的当前布局:

{
    "numOfQues": 5,
    "questions": [
        {
            "question": "Who is the US President?",
            "options": [
              "Joe Biden",
              "Joe BIREN",
              "Joe Momma",
              "Joe Bein"
            ],
            "answer": 2
        },
        {
            "question": "Who scored the best goal in Puskas history?",
            "options": [
              "Erik Lamela",
              "Son Heung-Min",
              "Cristiano Ronaldo",
              "Wayne Rooney"
            ],
            "answer": 4
        },
        {
            "question": "Where should Lamela really have finished?",
            "options": [
              "First",
              "Second",
              "Third",
              "Fourth"
            ],
            "answer": 3
        },
        {
            "question": "What does Conor love?",
            "options": [
              "Breaking curbs",
              "Breathing",
              "Having shit football opinions",
              "Being from Carlow"
            ],
            "answer": 1
        },
        {
            "question": "Who is the best footballer ever?",
            "options": [
              "Eric Dier",
              "Emile Heskey",
              "Bobby Zamora",
              "Phil Jones"
            ],
            "answer": 4
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

小智 7

Nlohmann JSON可能是最容易用于您的应用程序的,并且它遵循现代 C++ 原则。将单个包含(仅标头实现)和 JSON 文件放置在项目目录中。

用法示例:

#include "json.hpp"
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
    ifstream fJson("questions.json");
    stringstream buffer;
    buffer << fJson.rdbuf();
    auto json = nlohmann::json::parse(buffer.str());

    cout << "\nNumber of questions: " << json["numOfQues"] << "\n";

    for (auto question : json["questions"])
    {

        cout << question["question"] << "\n\n";
        int qCount = 0;
        for (auto opt : question["options"])
        {
            qCount++;
            cout << qCount << ". " << opt << "\n";
        }
        cout << "Answer: " << question["answer"] << "\n";
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

Number of questions: 5
"Who is the US President?"

1. "Joe Biden"
2. "Joe BIREN"
3. "Joe Momma"
4. "Joe Bein"
Answer: 2

"Who scored the best goal in Puskas history?"

1. "Erik Lamela"
2. "Son Heung-Min"
3. "Cristiano Ronaldo"
4. "Wayne Rooney"
Answer: 4

"Where should Lamela really have finished?"

1. "First"
2. "Second"
3. "Third"
4. "Fourth"
Answer: 3

"What does Conor love?"

1. "Breaking curbs"
2. "Breathing"
3. "Having shit football opinions"
4. "Being from Carlow"
Answer: 1

"Who is the best footballer ever?"

1. "Eric Dier"
2. "Emile Heskey"
3. "Bobby Zamora"
4. "Phil Jones"
Answer: 4
Run Code Online (Sandbox Code Playgroud)