Let’s say I have a dictionary in a .json file, created from a Python dictionary and dumped into this file with json.dump(my_dict, open("file.json", "r"), indent=4)
:
{
"Amazon": {
"email": "[email protected]",
"password": "123456",
}
}
{
"Stack Overflow": {
"email": "[email protected]",
"password": "password",
}
}
How would I access one of the two dictionaries later in my Python code? There are multiple dictionaries so I can’t simply read the .json file to get one and only one dictionary.
I’ve tried something like assigning the json.dump()
part to a variable but it still couldn’t access a specific dictionary. Basically, the main issue is that I don’t have variable-assigned dictionaries or something else to find one particular .json dictionary. Any help would be appreciated. Thanks!
2
Answers
If you update your file to contain a single JSON object, you can access the dictionaries within it using the json.load() function.
You do not have a JSON file. You have a file that is a concatenation of multiple JSON documents.
json.load
cannot handle this; you have to go lower level withJSONDecoder.raw_decode
. This code will load your file into a list:(assuming the file doesn’t actually have trailing commas before closing braces)
Of course, if you only wish to read the
n
-th record, you can stop reading after having readn
records, instead of accumulating the results in a list.Note that this is not a standard format. Not all programming languages allow you to JSON-parse a prefix of a string (e.g. in JavaScript you would either have to write a custom parser from scratch, or hack the error message to see where the error occured so you can cut the string off there — neither option is pretty). Use standard formats wherever possible. For example, JSONL (the same format but unindented, with one JSON document per line) is easily parseable in any language because you can predictably cut the raw string into lines before JSON parsing commences, while still being appendable, like your format.