繁体   English   中英

在使用 python “字符串索引必须是整数”的 JSON 导入中出现错误

[英]Getting an error in JSON Import with python “string indices must be integers”

import json

json_dump = json.dumps('1.json')

json_object = json.loads(json_dump)

print(json_object["client_id"])

我正在 python 中编写代码,该代码从 json 文件中提取 email 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"])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM