1

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?

2
  • 1
    If you don't want to have the movie ID be the key, you might be better off using a database like pythons built-in SQLite support. Commented Jul 6, 2015 at 21:54
  • So is the issue that you don't know how to cast the value of id from an integer to a string? I don't see why you can't use your original structure. Commented Jul 6, 2015 at 22:23

1 Answer 1

3

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)]

Sign up to request clarification or add additional context in comments.

1 Comment

I would like to do that (as you can see in my example) but numerical strings are not valid json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.