You should pass the file contents (i.e. a string) to json.loads(), not the file object itself. Try this:
with open(file_path) as f:
data = json.loads(f.read())
print(data[0]['text'])
There's also the json.load() function which accepts a file object and does the f.read() part for you under the hood.
You should pass the file contents (i.e. a string) to json.loads(), not the file object itself. Try this:
with open(file_path) as f:
data = json.loads(f.read())
print(data[0]['text'])
There's also the json.load() function which accepts a file object and does the f.read() part for you under the hood.
Use json.load(), not json.loads(), if your input is a file-like object (such as a TextIOWrapper).
Given the following complete reproducer:
import json, tempfile
with tempfile.NamedTemporaryFile() as f:
f.write(b'{"text": "success"}'); f.flush()
with open(f.name,'r') as lst:
b = json.load(lst)
print(b['text'])
...the output is success.
I'm supposed to create a dictionary from the values in a file and search for 'Polly' and remove it if it's in the file,
I kept getting errors so I'm just trying to get it to print the value just so I can see what I'm doing wrong and even at the most simple level I keep getting errors,
I'm in my first semester so this is all still new to me
employees = {}
employees = open('dictionary_values.txt', 'r')
print(employees['Polly'])
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(employees['Polly'])
TypeError: '_io.TextIOWrapper' object is not subscriptable
json.load() is for loading a file. json.loads() works with strings.
3 ways to load a json file:
import json
import ast
with open(file_path) as file:
data1 = json.load(file)
data2 = json.loads(file.read())
data3 = ast.literal_eval(file.read())
You should use json.load whenever possible, but sometimes the JSON file is not strictly in the correct format (e.g. single quotes instead of double quotes). A solution is to use ast.literal_eval().