'link = read_file['url']['short'] TypeError: '_io.TextIOWrapper' object is not subscriptable

heyy guys i wrote a simple script to upload selected file. everythink work just fine until i decided to save output link to file and print it without other useless informations.

im getting this error:

Traceback (most recent call last):
  File "C:\Users\Jakub\PycharmProjects\uploader\main.py", line 16, in <module>
    link = read_file['url']['short']
TypeError: '_io.TextIOWrapper' object is not subscriptable

my code:

import requests
import json

url = 'https://api.anonfiles.com/upload'
file = input("File name: ")
files = {'file':(file, open(file, 'rb'))}
r = requests.post(url, files=files)

print(r.content)

with open('outputfile.json', 'w') as f:
    f.write(r.text)


with open("outputfile.json", "r") as read_file:
    link = read_file['url']['short']
    print(link)



Solution 1:[1]

It seems like you expect that opening a json file automatically converts the file into json data. It does not. You need to call json.load() on the file.

with open("outputfile.json", "r") as read_file:
    jsondata = json.load(read_file)
    link = jsondata['url']['short']
    print(link)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John Gordon