d = {
"Laptop": {
"sony": 1,
"apple": 2,
"asus": 5,
},
"Camera": {
"sony": 2,
"sumsung": 1,
"nikon" : 4,
},
}
with open("my.json","w") as f:
json.dump(d,f)
Answer from Joran Beasley on Stack OverflowParsing JSON nested Dictionary using Python - Stack Overflow
Nested Dictionary for JSON data
How to reference nested dictionaries through JSON?
How can i convert python nested dictionary to json file? - Stack Overflow
Videos
To understand how your json is set up, it's easier to break it down. Let's look at the first dictionary's keys, and remove the values.
json = {"items": [], "links": {}}
You have a dictionary with two keys and two values. All three of the variables you are looking for (id, self, name) are in the first key, "items". So let's dive deeper.
json["items"] = [{'links': {'self': 'https://www.google.com'}, 'name': 'beast', 'type': 'Device', 'id': '12345'}]
Now you have a list containing a dictionary with the values you are looking for, so let's enter the first and only value of the list containing the next dictionary.
json["items"][0] = {'links': {'self': 'https://www.google.com'}, 'id': '12345', 'type': 'Device', 'name': 'beast'}
Finally we have the dictionary with the values are looking for, so you can use this code to find name and id.
json["items"][0]["name"] = beast
json["items"][0]["id"] = 12345
The self variable is hidden one dictionary deeper so we have to delve into the links key.
json["items"][0]["links"]["self"] = http://google.com
Now you have all of your values, you just need to follow through all the lists and dictionaries to get the value you want.
You can write a function, that will get the values you need:
def dict_get(x,key,here=None):
x = x.copy()
if here is None: here = []
if x.get(key):
here.append(x.get(key))
x.pop(key)
else:
for i,j in x.items():
if isinstance(x[i],list): dict_get(x[i][0],key,here)
if isinstance(x[i],dict): dict_get(x[i],key,here)
return here
dict_get(a,'id')
['12345']
dict_get(a,'self')
['https://www.google.com', 'https://www.google.com']
dict_get(a,'name')
['beast']
You can as well call any key that you want:
data
a = {
"items": [
{
"id": "12345",
"links": {
"self": "https://www.google.com"
},
"name": "beast",
"type": "Device"
}
],
"links": {
"self": "https://www.google.com"
},
"paging": {
"count": 1,
"limit": 1,
"offset": 0,
"pages": 1
}
}
import re, json, requests url = 'https://raw.githubusercontent.com/Fyresite/US-City-State-Zip-Master-JSON/master/states.json' resp = requests.get(url) resp_parsed = re.sub(r'^jsonp\d+\(|\)\s+$', '', resp.text) data = json.loads(resp_parsed)
print(data.items)
if isinstance(data, dict):
print(data.items())
for key,value in data.items():
for i,j in value.items():
for k,l in j.items():
print([key,k,l])
I am getting the below error when I am trying to print State, City & Zip code, because this is a nested dictionary where the structure as follows:
( [StateCode , {cities :{ cityName:[Zipcode]}, name:'StateName')])
AttributeError Traceback (most recent call last) Input In [85], in <cell line: 1>() 1 for key,value in data.items(): 2 for i,j in value.items(): ----> 3 for k,l in j.items(): 4 print([key,k,l]) AttributeError: 'str' object has no attribute 'items'
Please let me know how can I get the output printed as below:
| State | City | Zip |
|---|---|---|
| AK | Akhiok | 99615 |
Thank you in advance.
I have a nested dictionary inside a JSON file. It contains a header dictionary and one of the values is another dictionary called count. This dictionary gets a new key and value Everytime the program runs. Or at least it was supposed to, but I haven't found a way to reference the actual right value of count{} when running the code. I tried doing this in pickle but it lead to way too many problems. So I'm trying with JSON.
In a nutshell: Have a nested dictionary saved in JSON. The dictionary inside the dictionary needs some name to use as reference inside the program which looks for it when running, and adds a new key-value pair. How do I find the right names for these objects inside objects?
I really need this, any help is appreciated!
import json
data = {
'item1': {
'name': "A",
'price': 10
},
'item2': {
'name': "B",
'price': 20
}
}
print(list(data.values()))
json.dump(list(data.values()), f)
The problem is not about JSON but about having a dictionary and expecting a list.
You can convert your dictionary entries to a list with list(data.values()) and then export it to JSON.
json.dumps() converts a dictionary to str object, not a json(dict) object! So you have to load your str into a dict to use it by using json.loads() method
See json.dumps() as a save method and json.loads() as a retrieve method.
This is the code sample which might help you understand it more:
import json
r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
loaded_r['rating'] #Output 3.5
type(r) #Output str
type(loaded_r) #Output dict
json.dumps() returns the JSON string representation of the python dict. See the docs
You can't do r['rating'] because r is a string, not a dict anymore
Perhaps you meant something like
r = {'is_claimed': 'True', 'rating': 3.5}
json = json.dumps(r) # note i gave it a different name
file.write(str(r['rating']))