我正在尝试打开一个 json 文件.并将其存储为 JSON 对象

I am trying to open a file that is a json. and store it as an json object.

本文关键字:文件 json 存储 对象 JSON 一个      更新时间:2023-10-16

我正在尝试打开一个具有json扩展名的文件并将其存储为对象。 但是,不断收到一条错误消息,指出文件名未在作用域中声明。 我是使用 json 文件的新手。 您对待它们的方式是否与普通文本文件不同?

#include "json.hpp"
#include <iostream> 
#include <stdio.h> 
#include <fstream>
#include <string>

int main(int argc, char** argv) {
std::ifstream file;
file.open(test.json);
nlohmann::json jsonObject;
// Store the contents filename into jsonObject
if (file.is_open()) {
  file >> jsonObject;
}
file.close();
}

test.json作为文件名传递给open -函数。因此,编译器假定名为 test 的对象具有数据成员 json 。除非在代码中定义了这样的对象,否则编译器会告诉您作用域中没有名为test的对象。这就是原因。

你可能的意思是...

if (file.open("test.json")) {
   ...