M. Wombat
M. Wombat

Reputation: 55

JSON Website response into Python dictionary

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

Upvotes: 2

Views: 124

Answers (2)

Apoorva Srivastava
Apoorva Srivastava

Reputation: 388

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

Upvotes: 0

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

In order to iterate over each movie, Use:

json_object = json.loads(response.text)
for movie in json_object['movies']:
    print movie['movieTitle']

Upvotes: 1

Related Questions