简体   繁体   中英

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"])

I am writing a code in python which extracts email id from a json file. But I am getting an error:-

" string indices must be integers "

Here is the JSON FIle i am importing:-

  {
  "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"
  }

You should first open the file, and pass the opened file in 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

for looping over json files named as numbers

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"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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