python - 使用python“字符串索引必须是整数”在JSON导入中出现错误
问题描述
import json
json_dump = json.dumps('1.json')
json_object = json.loads(json_dump)
print(json_object["client_id"])
我正在用 python 编写一个从 json 文件中提取电子邮件 ID 的代码。但我收到一个错误:-
" 字符串索引必须是整数 "
这是我要导入的 JSON 文件:-
{
"type": "Some Data",
"project_id": "Some Data",
"private_key_id": "Some Data",
"private_key": "Some Data",
"client_email": "Some Data",
"client_id": "Some Data",
"auth_uri": "Some Data",
"token_uri": "Some Data",
"auth_provider_x509_cert_url": "Some Data",
"client_x509_cert_url": "Some Data"
}
解决方案
您应该首先打开文件,并将打开的文件传入json.load(file)
import json
# opening the json file
json_file = open('1.json','r+')
json_object = json.load(json_file)
print(json_object["client_id"])
Output:
Some Data
循环遍历以数字命名的 json 文件
import json
# opening the json file
# files named as 1.json to 3.json will do this
for i in range(1,4):
json_file = open(str(i)+'.json','r+')
json_object = json.load(json_file)
print(json_object["client_id"])
推荐阅读
- python - Pandas Sum DataFrame 各种类型的列
- msys2 - MSYS2 不断重置设置
- r - 随窗口变化的移动平均线
- javascript - 将离子标签从 ts 文件附加到 html
- git - 在 http auth 上使用 @ 字符进行 git pull
- symfony - Symfony 2.8 中的教义分析
- android - 将图像视图居中并使其占屏幕宽度的 50% 而没有约束线?
- powershell - 如何删除 CSV 中以“#”开头或空白的行 | 电源外壳
- python-3.x - 我正在尝试从某个容器中获取所有链接,但是对于 html 中的每个“href”,我得到了“无”的输出
- html - 如何在 Jekyll 博客中更改代码片段背景