Json 'list' object has no attribute 'get' - python

I have a json list like this:
{
"usuarios": [
{
"id": 1,
"nome": "vitor",
"email": "vitor#"
}
]
}
And I try to list this items using Python like this:
#!/usr/bin/python
import requests
import json
import sys
def list_users():
response = json.loads(requests.get("http://127.0.0.1:3000/usuarios/")._content)
for r in response.get("usuarios"):
print r["id"],r["nome"],r['email']
if __name__ == '__main__':
list_users()
And when I run, appear this error:
python rest_cli.py
Traceback (most recent call last):
File "rest_cli.py", line 62, in <module>
listar_usuarios()
File "rest_cli.py", line 10, in listar_usuarios
for r in response.get("usuarios"):
AttributeError: 'list' object has no attribute 'get'
How can I fix it?

URL in the following code is already giving you an array as response.
response = json.loads(requests.get("http://127.0.0.1:3000/usuarios/")._content)
Don't do a get on the response. Just use a simple for loop on it like :
for r in response:
print r["id"],r["nome"],r['email']

That is a namespace issue as you are importing everything from requests I believe. Remove the .get and just use requests.
requests("http://127.0.0.1:3000/usuarios/")._content

Related

Get Value Of API Dictionary

I'm using a service with an API key and I want to print my balance.
from requests_html import HTMLSession
session = HTMLSession()
r = session.post('https://api.anycaptcha.com/getBalance', data = {'clientKey': API})
Everything works. When I do print(r.text) the following dictionary gets print:
{"errorId":0,"errorCode":"SUCCESS","balance":20.0}
However, I just want to get the value of "balance" (20.0). But I couldn't figure out how.
What I tried:
print(r.text['balance'])
# Output:
Traceback (most recent call last):
File "X/test.py", line 7, in <module>
print(r.text['balance'])
TypeError: string indices must be integers
Try this, as r.text is a string with your dict
import json
d = json.loads(r.text)
#Now you can access dict
d["balance"]

How to to access different JSON keys?

I have a JSON file as the following, and I'm trying to access those different keys with Python.
My JSON file format:
{
"spider":[
{
"t":"Spider-Man: No Way Home (2021)",
"u":"movie\/spider-man-no-way-home-2021",
"i":"c2NJbHBJYWNtbW1ibW12Tmptb1JjdndhY05FbXZhS1A"
},
{
"t":"Spider-Man: Far from Home (2019)",
"u":"movie\/spider-man-far-from-home-2019",
"i":"c2NJbHBJYWNtTGNtdm1qbXZtYm1FRWNtcEV4bWJ4bWJteGo"
},
{
"t":"Spider-Man: Homecoming (2017)",
"u":"movie\/spider-man-homecoming-2017",
"i":"c2NJbHBJYWN2TllqbVRibXVjbWJ2d3h2dGNtam1idmM"
},
{
"t":"Spider-Man: Into the Spider-Verse (2018)",
"u":"movie\/spider-man-into-the-spider-verse-2018",
"i":"c2NJbHBJYWNtVEVtdnZjbXZtdm1qRWNtYnhtR1VURXZjY3c"
},
{
"t":"Spider-Man (2002)",
"u":"movie\/spider-man-2002",
"i":"c2NJbHBJYWNtam1ZanZjbWptakVjbXZtdm1oenh2Y3htSQ"
},
{
"t":"The Spiderwick Chronicles (2008)",
"u":"movie\/the-spiderwick-chronicles-2008",
"i":"c2NJbHBJYWNtVG9Oam1qbWJFY21ibWJ2d1BtYm1tbUhj"
}
]
}
How I can access the t, u, and i keys?
I tried:
print(json_file['t'])
Nothing helped with the error:
Traceback (most recent call last):
File "/home/werz/Desktop/trying/programming/nutflix/flask-nutflix/test.py", line 38, in <module>
print (json_file['t'])
KeyError: 't'
Try indexing for printing like
print(json_file["spider"][1]["t"])
You can try for loop to print all
You can use python's builtin JSON module, and iterate through the spider key of your json object.
import json#import the builtin json library
with open('file_path') as file:#open the file
text=f.read()#read the contents of the file
json_data=json.loads(text)#turn the file into a json object
t=[]#List of the t
u=[]#List of the u
i=[]#List of the i
for film in json_data['spider']:#iterate through films
t.append(film['t'])#store the data for these films
u.append(film['u'])
i.append(film['i'])
You can use Json module to load and read json files. Please find the example where i am getting 't' values. Write the same for 'u' and 'i'.
import json
# Opening JSON file
f = open('myJson.json', )
# returns JSON object as a dictionary
data = json.load(f)
# Iterating through the json list
for i in data['spider'][:]:
print(i['t'])
# Closing file
f.close()
Hope this will help. :)

TypeError when trying to get data from JSON

I would like to print specific data in a JSON but I get the following error:
Traceback (most recent call last):
File "script.py", line 47, in <module>
print(link['data.file.url.short'])
TypeError: 'int' object has no attribute '__getitem__'
Here is the JSON:
{
"status":true,
"data":{
"file":{
"url":{
"full":"https://anonfile.com/y000H35fn3/yuh_txt",
"short":"https://anonfile.com/y000H35fn3"
},
"metadata":{
"id":"y000H35fn3",
"name":"yuh.txt",
"size":{
"bytes":0,
"readable":"0 Bytes"
}
}
}
}
}
I'm trying to get data.file.url.short which is the short value of the url
Here is the script in question:
post = os.system('curl -F "file=#' + save_file + '" https://anonfile.com/api/upload')
link = json.loads(str(post))
print(link['data.file.url.short'])
Thanks
Other than os.system() return value mentioned by #John Gordon I think correct syntax to access data.file.url.short is link['data']['file']['url']['short'], since json.loads returns dict.
os.system() does not return the output of the command; it returns the exit status of the command, which is an integer.
If you want to capture the command's output, see this question.
You are capturing the return code of the process created by os.system which is an integer.
Why dont you use the request class in the urllib module to perform that action within python?
import urllib.request
import json
urllib.request.urlretrieve('https://anonfile.com/api/upload', save_file)
json_dict = json.load(save_file)
print(json_dict['data']['file']['url']['short']) # https://anonfile.com/y000H35fn3
Or if you don't need to save the file you can use the requests library:
import requests
json_dict = requests.get('https://anonfile.com/api/upload').json()
print(json_dict['data']['file']['url']['short']) # https://anonfile.com/y000H35fn3

How to print from response object

I'm currently trying to get data with python from the Internet. Fortunately the Website I want to Approach Hands me the data in json Format.
Now this is my Code:
from GetWebJson import simple_get
import json
raw_data = simple_get('http://api.openweathermap.org/data/2.5/weather?q=Hamburg,de')
raw_data.encoding
data_json = raw_data.json
print(data_json["temp"])
The simple_get function executes "Get" from the requests library and Returns the Response object.
After formatting the raw data to json In want to print the value of the key "temp". But when i debug this Code I get the following error:
Traceback (most recent call last):
File "C:\Users\nikhi\source\repos\WebScraper\WebScraper\WebScraper.py", line 7, in
print(data_json["temp"])
TypeError: 'method' object is not subscriptable
Can't I use the variable data_json like a dict? If not, how do I convert the json, which contains lists and dicts to a printable Format?

NameError in function to retrieve JSON data

I'm using python 3.6.1 and have the following code which successfully retrieves data in JSON format:
import urllib.request,json,pprint
url = "https://someurl"
response = urllib.request.urlopen(url)
data = json.loads(response.read())
pprint.pprint(data)
I want to wrap this in a function, so i can reuse it. This is what i have tried in a file called getdata.py:
from urllib.request import urlopen
import json
def get_json_data(url):
response = urlopen(url)
return json.loads(response.read())
and this is the error i get after importing the file and attempting to print out the response:
>>> import getdata
>>> print(getdata.get_json_data("https://someurl"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Nick\getdata.py", line 6, in get_json_data
from urllib.request import urlopen
NameError: name 'urllib' is not defined
i also tried this and got the same error:
import urllib.request,json
def get_json_data(url):
response = urllib.request.urlopen(url)
return json.loads(response.read())
What do i need to do to get this to work please?
cheers
Its working now ! I think the problem was the hydrogen addon i have for the Atom editor. I uninstalled it, tried again and it worked. Thanks for looking.

Categories