在用python导入JSON时得到一个错误 "字符串索引必须是整数"

问题描述 投票:0回答:1
import json

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

json_object = json.loads(json_dump)

print(json_object["client_id"])

我正在用Python编写一段代码,从json文件中提取电子邮件ID,但我得到了一个错误:-。

"字符串索引必须是整数"

下面是我导入的JSON FIle:-。

  {
  "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"
  }
python json python-3.x string indices
1个回答
0
投票

你应该首先打开文件,并将打开的文件传入 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"])
© www.soinside.com 2019 - 2024. All rights reserved.