1

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
Sahil
  • 1,387
  • 14
  • 41
  • 2
    Can you show the output for `print(j)`? – pissall Sep 09 '19 at 04:03
  • It seems that you are iterating on the keys of a mapping. Check what ``j`` is instead of trying to print is elements. – MisterMiyagi Sep 09 '19 at 04:10
  • Possible duplicate of [Iterating over dictionaries using 'for' loops](https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops) – Shadow Sep 09 '19 at 04:14
  • if it is dictionary then loop normally gives only keys. You would have to use `data.items()` in `for..in...` to get pairs `(key, value)` . But first you should check `print(data)` and `print(type(data))` – furas Sep 09 '19 at 20:38

2 Answers2

3

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']
Matthew Gaiser
  • 4,558
  • 1
  • 18
  • 35
0

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.

Nyzex SKB
  • 156
  • 5