How do I get individual userId, id, title and posts from jsonplaceholder.typecode.com
Question:
I need help with an assignment regarding API calls. Here are the following parameters:
-
use python to get on Api (https://jsonplaceholder.typicode.com)
import requests, json
url = 'https://jsonplaceholder.typicode.com/posts'
r = requests.get(url)
data = json.loads(r.text)
-
capture list of dictionaries from one endpoint and reverse sort
for item in reversed(data):
print(item)
-
Print a post for specific userId
print(data[0])
-
Print a post from specific userId that only prints out the title, id, or post
When I try:
print(data[0].id[1])
I get a ‘dict’ object has no attribute ‘id’. Any help is appreciated. I just need help with question 4.
Answers:
To access dictionary element in python you use dictionary['<key>']
(not dictionary.<key>
). Try:
print(data[0]['id'])
print(data[0]['userId'])
I need help with an assignment regarding API calls. Here are the following parameters:
-
use python to get on Api (https://jsonplaceholder.typicode.com)
import requests, json url = 'https://jsonplaceholder.typicode.com/posts' r = requests.get(url) data = json.loads(r.text)
-
capture list of dictionaries from one endpoint and reverse sort
for item in reversed(data): print(item)
-
Print a post for specific userId
print(data[0])
-
Print a post from specific userId that only prints out the title, id, or post
When I try:
print(data[0].id[1])
I get a ‘dict’ object has no attribute ‘id’. Any help is appreciated. I just need help with question 4.
To access dictionary element in python you use dictionary['<key>']
(not dictionary.<key>
). Try:
print(data[0]['id'])
print(data[0]['userId'])