用 C++ 读取 JSON 文件
本文将解释创建 JSON 文件,然后在编译器中从该文件读取数据的概念。 我们将使用 C++ 语言和 jsoncpp 库。
本文使用Linux操作系统来完成上述任务。 不过,也可以在 Windows 操作系统上的 C++ 编译器中完成。
我们必须安装读取 JSON 文件所需的库。 我们将了解如何在虚拟机上安装 Linux,然后安装必要的库来执行我们的程序。
我们必须在代码片段中包含以下库来读取 JSON 文件。
#include<iostream> // This library defines standard input/ output objects
#include<jsoncpp/json/value.h> //This library is used for interacting with JSON file
#include<jsoncpp/json/json.h>
#include<fstream> // This library is used for reading and writing data to the files
#include<string> // This library is used to store text
JSON 文件
JSON 代表 JavaScript 对象表示法。 JSON 用于存储和交换数据。
它与 JavaScript 无关。 JSON 是客户端和服务器计算机之间用于发送和接收数据的数据格式。
我们在 JSON 中有不同的对象。 键及其值对包含在花括号中。
JSON 是一种轻量级数据格式。 JSON 不支持注释和命名空间。
JSON 的格式如下。
var person={"firstname":"Ali","Lastname":"Ahmad"};
JSON 中允许有六种数据类型。
- String
- Number
- Boolean
- Array
- Object
- Null
{
"name": "ali",
"age" : 30,
"married": false,
"kids" : ,
"hobbies": ["music","sports"],
"vehicle":{
{"type": "car", "vname": "swift"},
{"type": "bike", "vname": "honda"}
}
};
第一个是 String,第二个是 Number,第三个是 Boolean,第四个是 Null,第五个是 Array,第六个是 Object。 这是人类可读的格式。
从 JSON 文件读取数据 首先,我们必须按照以下步骤在 Windows 上下载并安装 Ubuntu。 通过 Virtual Box 在计算机上安装 Ubuntu 的步骤。
安装 Ubuntu 后,我们将看到这个屏幕。
我们必须通过单击具有九个点的图标来搜索终端。 然后会出现一个搜索栏,我们必须在该屏幕上输入terminal。
然后,在获得此终端后,我们首先必须通过键入以下命令来安装编译器。
sudo apt install gcc
此后,您必须输入登录密码并输入 Y(表示“是”)才能安装软件包。
安装完成后,我们必须在 dev 中安装 JSON 库。
sudo apt install libjson-cpp-dev
安装这个 JSON 库后,我们必须打开文本编辑器并在 JSON 文件中写入以下代码。
{
"Name":"Alice",
"Dob" : "17th october 2022",
"College" : "Kips"
}
下面的代码片段将解释如何用C++读取JSON文件。
#include<iostream>
#include<jsoncpp/json/value.h>
#include<jsoncpp/json/json.h>
#include<fstream>
#include<string>
using namespace std;
int main() {
//Using fstream to get the file pointer in file
ifstream file("file.json");
Json::Value actualJson;
Json::Reader reader;
//Using the reader, we are parsing the json file
reader.parse(file, actualJson);
// The actual json has the json data
cout<< "Total json data:\n"<<actualJson << endl;
//accessing individual parameters from the file
cout<<"Name:"<< actualJson["Name"] <<endl;
cout<<"Dob:"<< actualJson["Dob"]<< endl;
cout<<"College:"<<actualJson["College"]<<endl;
return 0;
}
首先,该代码包括输入/输出函数库、从文件中读取数据以及读取字符。 然后 JSON.h 是您访问所有函数所需的标头。
然后我们使用fstream来获取文件中的文件指针。 打开JSON文件后,我们使用Reader函数解析文件以读取文件内容。
然后使用C++中的输出函数将JSON文件中的所有数据显示在屏幕上。 然后我们从 JSON 文件中访问各个参数的值并将其显示在屏幕上。
上面的代码用于从JSON文件中读取数据。 写完上面的代码后,我们必须使用命令来编译并执行它。
g++ test.cpp -ljsoncpp
./a.out
输出:
相关文章
Arduino 复位
发布时间:2024/03/13 浏览次数:315 分类:C++
-
可以通过使用复位按钮,Softwarereset 库和 Adafruit SleepyDog 库来复位 Arduino。
Arduino 的字符转换为整型
发布时间:2024/03/13 浏览次数:181 分类:C++
-
可以使用简单的方法 toInt()函数和 Serial.parseInt()函数将 char 转换为 int。
Arduino 串口打印多个变量
发布时间:2024/03/13 浏览次数:381 分类:C++
-
可以使用 Serial.print()和 Serial.println()函数在串口监视器上显示变量值。