So I have a data in json file which i never worked before.When I load and try print the data by index like print(data[0])
I got and warning
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/app/extra/plugins/python/helpers/pydev/_pydev_bundle/pydev_umd.py", line 198, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "/app/extra/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents "\n", file, 'exec'), glob, loc)
File "/home/levi/PycharmProjects/Topic-Modelling/main.py", line 37, in <module>
print(data[0])
KeyError: 0
But When I print it like a print(data["0"])
the result as fine as expected.So I am confused the dict indexes change to string not integer.Can anyone tell me how to resolve this problem by change the keys into int.My code is like this
import json
def load_data(file):
with open(file, "r", encoding="utf-8") as f:
data = json.load(f)
return data
def write_data(file, data):
with open(file, "w", encoding="utf-8") as f:
json.dump(data, f, indent=4)
data = load_data("file.json")["teks"]
print(data["0"])
CodePudding user response:
This is expected behaviour. In JSON, object keys are always strings. The integer 0
is not a valid key. Integers are only valid for accessing JSON arrays.
CodePudding user response:
You can do the conversion of keys to int as part of your read function.
def load_data(file):
with open(file, "r", encoding="utf-8") as f:
data = json.load(f)
return {int(k): v for k, v in data.items()}
When writing to the json file, json.dump()
will still write the keys as strings for it to be valid json, but after reading from the file, you will be able to access data[0]
If you have some keys that are strings and some that are integers, you could try to convert to int
, and in case an error occurs, skip the conversion.
def load_data(file):
with open(file, "r", encoding="utf-8") as f:
data = json.load(f)
d = dict()
for k, v in data.items():
try:
d[int(k)] = v
except ValueError:
d[k] = v
return d