Reputation: 13206
I have a complex document that I am trying to structure most conveniently and efficiently with JSON in Python. I would like to be able to retrieve one of the items in my document with one line (i.e. not via a for
loop)
A demo of the structure looks like this:
{
"movies": {
"0": {
"name": "charles",
"id": 0,
"loopable": true
},
"1": {
"name": "ray",
"id": 1,
"loopable": true
}
}
}
I am trying to be able to easily fetch a movie based on its id
field. To do this, right now, I have made the index
the same as the key to the movies object. So when I json.load
the object to find movie 1
's name I can just do movie[(id)]['name']
It seems like I should have a list
of movies in the json file but it also seems like that would be more complicated. It could look like this:
{
"movies": [
{
"name": "charles",
"id": 0,
"loopable": true
},
{
"name": "ray",
"id": 1,
"loopable": true
}
]
}
but if that were the case I would have to loop through the entire array like this:
for movie in movies:
if movie['id'] == (id)
# Now I can get movie['id']['name']
Is there a more effiecient way of doing this?
Upvotes: 1
Views: 256
Reputation: 18940
Let 'movies'
be a dict and not a list:
{
"movies": {
"12": {
"name": "charles",
"id": 12,
"loopable": true
},
"39": {
"name": "ray",
"id": 39,
"loopable": true
}
}
}
and you can access movie by id with yourjson['movies'][str(id)]
Upvotes: 3