2

I'm trying to load a JSON response from a website into a Python (2.7) dictionary, but am getting stuck iterating through more than the outer JSON object.

E.g. the website response looks like:

{
  "movies": [
    {
      "movieTitle": "True Lies",
      "Cert": "15",
      "Released": "1987",
    },
     {
      "movieTitle": "Scary Movie",
      "Cert": "18",
      "Released": "1997",
    },

My Python is as follows, and when printing 'json_object' I see all of the data, but how can I get the JSON array held within 'json_object' into a Python list / dictionary?

response = requests.get('https://api.foo.com/movies/all', headers=headers)
json_object = json.loads(response.text)
print json_object
1
  • 3
    The question is unclear. json_object is a dict; json_object["movies"] is a list. Where exactly are you having problems? Commented Mar 8, 2016 at 8:58

2 Answers 2

1

In order to iterate over each movie, Use:

json_object = json.loads(response.text)
for movie in json_object['movies']:
    print movie['movieTitle']
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, this was the missing link in my logic. Many thanks :)
0

Try using json.loads. It shall convert your json into a python dictionary and you can access the elements now and manipulate them as you normall would in a python dict.

dict1 = json.loads(json_object)

For eg, to obtain the movie title:

title = dict1["movies"][0]["movietitle"]

2 Comments

How does this help? OP is already using json.loads, as shown in the code.
This is wrong too. dict1['movies'] is a list. This will throw an error

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.