写一个从JSON文档里抓取特定信息的程序 
时间: 2023-06-01 20:02:56 浏览: 20
以下是一个从JSON文档里抓取特定信息的Python程序的示例:
```python
import json
# 读取JSON文档
with open('example.json', 'r') as f:
data = json.load(f)
# 抓取特定信息
name = data['name']
age = data['age']
email = data['contact']['email']
# 输出结果
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Email: {email}")
```
在这个示例中,我们首先使用`json.load()`方法将JSON文档读入程序。然后,我们从数据中抓取了名字、年龄和电子邮件地址,并将它们存储在变量中。最后,我们输出这些信息。请注意,在这个示例中,我们假设JSON文档的格式如下:
```json
{
"name": "John Doe",
"age": 32,
"contact": {
"email": "johndoe@example.com",
"phone": "555-1234"
}
}
```
如果您的JSON文档具有不同的格式,您需要相应地修改程序以抓取所需的信息。
相关问题
用qt写一个读入json文件的示例程序
好的,以下是一个用Qt读取JSON文件的示例程序:
```cpp
#include <QCoreApplication>
#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 打开JSON文件
QFile file("example.json");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "无法打开文件";
return -1;
}
// 读取JSON数据
QByteArray data = file.readAll();
QJsonDocument doc = QJsonDocument::fromJson(data);
if (doc.isNull()) {
qDebug() << "JSON数据格式错误";
return -1;
}
// 解析JSON对象
QJsonObject obj = doc.object();
QString name = obj["name"].toString();
int age = obj["age"].toInt();
// 输出结果
qDebug() << "姓名:" << name;
qDebug() << "年龄:" << age;
return a.exec();
}
```
希望这个示例程序能够帮助到你。
用c++写一个读入json文件的示例程序
当然可以,以下是一个简单的示例程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "cJSON.h"
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <json_file>\n", argv[0]);
return 1;
}
FILE *fp = fopen(argv[1], "r");
if (!fp) {
printf("Failed to open file: %s, error: %s\n", argv[1], strerror(errno));
return 1;
}
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *json_str = (char *)malloc(size + 1);
if (!json_str) {
printf("Failed to allocate memory\n");
fclose(fp);
return 1;
}
fread(json_str, 1, size, fp);
fclose(fp);
cJSON *root = cJSON_Parse(json_str);
if (!root) {
printf("Failed to parse json string\n");
free(json_str);
return 1;
}
cJSON *name = cJSON_GetObjectItem(root, "name");
if (name) {
printf("name: %s\n", name->valuestring);
}
cJSON *age = cJSON_GetObjectItem(root, "age");
if (age) {
printf("age: %d\n", age->valueint);
}
cJSON_Delete(root);
free(json_str);
return 0;
}
```
这个程序使用了
相关推荐









