简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM