Kateezy Mymoneygone
Kateezy Mymoneygone

Reputation: 13

How can I access these json object in python

I'm making some data visualization from movies database api and I already access the data in the normal way but when i load the json data and for loop to print it, the data that out is just the column but I need to access the object inside.

url = "https://api.themoviedb.org/3/discover/movie?api_key="+ api_key 
+"&language=en- US&sort_by=popularity.desc&include_adult=
false&include_video=false&page=1" # api url

response = urllib.request.urlopen(url)
raw_json = response.read().decode("utf-8")
data = json.loads(raw_json)

for j in data:
    print(j)

i expect the output would be

[{'popularity': 15,
  'id': 611,
  'video': False,
  'vote_count': 1403,
  'vote_average': 8.9,
  'title': 'lalalalo'},{....}]

but the actual output is

page
total_results
total_pages
results

Upvotes: 1

Views: 312

Answers (2)

Nyzex SKB
Nyzex SKB

Reputation: 156

you can simply use requests module...

import requests
import json

your_link = " "
r = requests.get(your_link)
data = json.loads(r.content)

You shall have the json loaded up, then use your key "results" ["results"] and loop through the data you got.

Upvotes: 0

Matthew Gaiser
Matthew Gaiser

Reputation: 4763

The results are one level down. You are looping through the metadata.

Try changing your code to

import json
import urllib.request
api_key = "your api code"

url = "https://api.themoviedb.org/3/discover/movie?api_key=" + api_key +"&language=en- US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1" # api url

response = urllib.request.urlopen(url)
raw_json = response.read().decode("utf-8")
data = json.loads(raw_json)

for j in data['results']:
    print(j)

You need to change

data

to

data['results']

Upvotes: 3

Related Questions