首页 > 解决方案 > 使用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"
  }

标签: pythonjsonpython-3.xstringindices

解决方案


您应该首先打开文件,并将打开的文件传入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"])

推荐阅读