If you update your file to contain a single JSON object, you can access the dictionaries within it using the json.load() function.
with open("file.json") as json_file:
items = json.load(json_file)
dict1 = items[0]
Answer from dev0717 on Stack OverflowI must first preface this with the fact that I’m extremely new to python. Like just started learning it a little over a week ago.
I have been racking my brain over how to convert a json object I opened and loaded into a dictionary from a list so I can use the get() function nested within a for loop to do a student ID comparison from another json file (key name in that file is just ID).
Below is the command I’m trying to load the json file:
With open(‘file.json’) as x: object=json.load(x)
When I print(type(object)), it shows up as class list.
Here’s a sample of what the json looks like:
[
{
“Name”: “Steel”,
“StudentID”: 3458274
“Tuition”: 24.99
},
{
“Name”: “Joe”,
“StudentID”: 5927592
“Tuition”: 14.99
}
]
HELP! Thank you!
How can I access a specific dictionary in JSON file in python? - Stack Overflow
python - How can I import the first and only dict out of a top-level array in a json file? - Stack Overflow
Correct way of loading JSON from file into a Python dictionary - Stack Overflow
How to read a json file and return as dictionary in Python - Stack Overflow
Videos
If you update your file to contain a single JSON object, you can access the dictionaries within it using the json.load() function.
with open("file.json") as json_file:
items = json.load(json_file)
dict1 = items[0]
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 with JSONDecoder.raw_decode. This code will load your file into a list:
import json
with open('file.json', 'rt') as r:
raw_json = r.read()
decoder = json.JSONDecoder()
items = []
while raw_json:
item, pos = decoder.raw_decode(raw_json)
raw_json = raw_json[pos:].strip()
items.append(item)
from pprint import pprint
pprint(items)
# => [{'Amazon': {'email': '[email protected]', 'password': '123456'}},
# {'Stack Overflow': {'email': '[email protected]',
# 'password': 'password'}}]
(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 read n 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.
Your data get's imported as list, because in your JSON file the main structure is an Array (squared brackets), which is comparable to a list in Python.
If you want just inner dict you can do
data = json.load(f)[0]
The accepted answer is correct, but for completeness I wanted to offer an example that is increasingly popular for people like me who search for "read json file into dict" and find this answer first (if just for my own reference):
# Open json file and read into dict
with open('/path/to/file.json') as f:
data = json.load(f)
# In the author's example, data will be a list. To get the dict, simply:
data = data[0]
# Then addressing the dict is simple enough
# To print "icon.svg":
print(data.get("image"))
Your data must have already been a JSON string to begin with and then you double-encoded it during
the json.dump. Then of course you need to double-decode it later. So instead of encoding the original JSON with JSON again, just write it to the file as-is:
with open(filename, 'w+') as f:
f.write(data)
Disclaimer: I don't know if this is the definite correct way, but it works for me:
jd0 = {
'foo': 1337,
'bar': 'baz'
}
# Dump it somewhere
with open('/Dump/it/somewhere/test.json', 'w') as fh:
json.dump(jd0, fh)
If I then load it, its a dict again:
with open('/Dump/it/somewhere/test.json', 'r') as fh:
jd1 = json.load(fh)
print type(jd1) == dict
Prints
True