Python3 Error: TypeError: 'str' object is not callable - json

I'd like to get the latest posts id from a subreddit. Reddit is have basic api for this. You can get json so i want gives data and decode it but i have a error.
root#archi-sunucu:~/yusuf/www# python3 reddit.py
Traceback (most recent call last):
File "reddit.py", line 24, in <module>
json = json.loads(resp.text())
TypeError: 'str' object is not callable
root#archi-sunucu:~/yusuf/www# python3 reddit.py
my code:
url = "https://www.reddit.com/r/" + subreddit + "/" + feed + ".json?sort=" + feed + "&limit=6"
resp = requests.get(url, verify=False)
json = json.loads(resp.text())
print(json["data"]["children"][0]["data"]["id"])
thanks for helps...

You complained that this expression raises an error:
json.loads(resp.text())
Well, let's break that down into something simpler,
so the line number tells us exactly what part of your code is failing.
temp = resp.text()
json.loads(temp)
Now we see that the 2nd line doesn't even execute,
it fails in the 1st line attempting to compute something
to assign to the temporary variable.
Examine resp and its attribute with tools
like help(resp), dir(resp), type(resp.text), repr(resp.text).
You will soon learn the .text attribute is a str.
That is not a callable function, so python raises an error.
Use the value directly, without a call:
json = json.loads(resp.text)

Related

Iterating through describe_instances() to print key & value boto3

I am currently working on a python script to print pieces of information on running EC2 instances on AWS using Boto3. I am trying to print the InstanceID, InstanceType, and PublicIp. I looked through Boto3's documentation and example scripts so this is what I am using:
import boto3
ec2client = boto3.client('ec2')
response = ec2client.describe_instances()
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
instance_id = instance["InstanceId"]
instance_type = instance["InstanceType"]
instance_ip = instance["NetworkInterfaces"][0]["Association"]
print(instance)
print(instance_id)
print(instance_type)
print(instance_ip)
When I run this, "instance" prints one large block of json code, my instanceID, and type. But I am getting an error since adding NetworkInterfaces.
instance_ip = instance["NetworkInterfaces"][0]["Association"]
returns:
Traceback (most recent call last):
File "/Users/me/AWS/describeInstances.py", line 12, in <module>
instance_ip = instance["NetworkInterfaces"][0]["Association"]
KeyError: 'Association'
What am I doing wrong while trying to print the PublicIp?
Here is the structure of NetworkInterfaces for reference:
The full Response Syntax for reference can be found here (https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_instances)
Association man not always may be present. Also an instance may have more then one interface. So your working loop could be:
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
instance_id = instance["InstanceId"]
instance_type = instance["InstanceType"]
#print(instance)
print(instance_id, instance_type)
for network_interface in instance["NetworkInterfaces"]:
instance_ip = network_interface.get("Association", "no-association")
print(' -', instance_ip)

reading JSON from file and extract the keys returns attribute str has no keys

I am new to Python (and JSON) so apologies of this is obvious to you.
I pull some data from an API using the following code
import requests
import json
headers = {'Content-Type': 'application/json', 'accept-encoding':'identity'}
api_url = api_url_base+api_token+api_request #variables removed for security
response = requests.get(api_url, headers=headers)
data=response.json()
keys=data.keys
if response.status_code == 200:
print(data["message"], "saving to file...")
print("Found the following keys:")
print(keys)
with open('vulns.json', 'w') as outfile:
json.dump(response.content.decode('utf-8'),outfile)
print("File Saved.")
else:
print('The site returned a', response.status_code, 'error')
this works, I get some data returned and I am able to write the file.
I am trying to change what's returned form a short format to a long format and to check its working I need to see the keys, I was trying to do this offline using the written file (as practice for reading JSON from files).
I wrote these few lines (taken from this site https://www.kite.com/python/answers/how-to-print-the-keys-of-a-dictionary-in-python)
import json
with open('vulns.json') as json_file:
data=json.load(json_file)
print(data)
keys=list(data.keys())
print(keys)
Unfortunately, whenever I run this it returns this error
Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print(keys)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'keys' is not defined
>>> & C:/Users/xxxx/AppData/Local/Microsoft/WindowsApps/python.exe c:/Temp/read-vulnfile.py
File "<stdin>", line 1
& C:/Users/xxxx/AppData/Local/Microsoft/WindowsApps/python.exe c:/Temp/read-vulnfile.py
^
SyntaxError: invalid syntax
>>> exit()
PS C:\Users\xxxx\Documents\scripts\Python> & C:/Users/xxx/AppData/Local/Microsoft/WindowsApps/python.exe c:/Temp/read-vulnfile.py
Traceback (most recent call last):
File "c:\Temp\read-vulnfile.py", line 6, in <module>
keys=list(data.keys)
AttributeError: 'str' object has no attribute 'keys'
The Print(data) command returns what looks like JSON, this is the opening line:
{"count": 1000, "message": "Vulnerabilities found: 1000", "data":
[{"...
I cant show the content it's sensitive.
why is this looking at a str object rather than a dictionary?
how do I read JSON back into a dictionary please?
You just have that content stored in file as a string. Just open the vulns.json in some editor and there most likely is something like "{'count': 1000, ... instead of {"count": 1000, ....
It's opened by json.load, but translated to string (see this table).
So you should take one step back and take a look what happens during saving to file. You take some content from your response, but dump the string decoded value into a file. Take instead a try with
json.dump(response.json(), outfile)
(or just use data variable you already have provided).
This should allow you to succesfully dump and load data as a dict.

JSON Parsing with Nao robot - AttributeError

I'm using a NAO robot with naoqi version 2.1 and Choregraphe on Windows. I want to parse json from an attached file to the behavior. I attached the file like in that link.
Code:
def onLoad(self):
self.filepath = os.path.join(os.path.dirname(ALFrameManager.getBehaviorPath(self.behaviorId)), "fileName.json")
def onInput_onStart(self):
with open(self.filepath, "r") as f:
self.data = self.json.load(f.get_Response())
self.dataFromFile = self.data['value']
self.log("Data from file: " + str(self.dataFromFile))
But when I run this code on the robot (connected with a router) I'll get an error:
[ERROR] behavior.box :_safeCallOfUserMethod:281 _Behavior__lastUploadedChoregrapheBehaviorbehavior_1136151280__root__AbfrageKontostand_3__AuslesenJSONDatei_1: Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/naoqi.py", line 271, in _safeCallOfUserMethod
func()
File "<string>", line 20, in onInput_onStart
File "/usr/lib/python2.7/site-packages/inaoqi.py", line 265, in <lambda>
__getattr__ = lambda self, name: _swig_getattr(self, behavior, name)
File "/usr/lib/python2.7/site-packages/inaoqi.py", line 55, in _swig_getattr
raise AttributeError(name)
AttributeError: json
I already tried to understand the code from the correspondending lines but I couldn't fixed the error. But I know that the type of my object f is 'file'. How can I open the json file as a json file?
Your problem comes from this:
self.json.load(f.get_Response())
... there is no such thing as "self.json" on a Choregraphe box, import json and then do json.load. And what is get_Response ? That method doesn't exist on anything in Python that I know of.
You might want to first try making a standalone python script (that doesn't use the robot) that can read your json file before you try it with choregraphe. It will be easier.

Python Json reference and validation

I'm starting using python to validate some json information, i'm using a json schema with reference but i'm having trouble to reference those files. This is the code :
from os.path import join, dirname
from jsonschema import validate
import jsonref
def assert_valid_schema(data, schema_file):
""" Checks whether the given data matches the schema """
schema = _load_json_schema(schema_file)
return validate(data, schema)
def _load_json_schema(filename):
""" Loads the given schema file """
relative_path = join('schemas', filename).replace("\\", "/")
absolute_path = join(dirname(__file__), relative_path).replace("\\", "/")
base_path = dirname(absolute_path)
base_uri = 'file://{}/'.format(base_path)
with open(absolute_path) as schema_file:
return jsonref.loads(schema_file.read(), base_uri=base_uri, jsonschema=True, )
assert_valid_schema(data, 'grandpa.json')
The json data is :
data = {"id":1,"work":{"id":10,"name":"Miroirs","composer":{"id":100,"name":"Maurice Ravel","functions":["Composer"]}},"recording_artists":[{"id":101,"name":"Alexandre Tharaud","functions":["Piano"]},{"id":102,"name":"Jean-Martial Golaz","functions":["Engineer","Producer"]}]}
And i'm saving the schema and reference file, into a schemas folder :
recording.json :
{"$schema":"http://json-schema.org/draft-04/schema#","title":"Schema for a recording","type":"object","properties":{"id":{"type":"number"},"work":{"type":"object","properties":{"id":{"type":"number"},"name":{"type":"string"},"composer":{"$ref":"artist.json"}}},"recording_artists":{"type":"array","items":{"$ref":"artist.json"}}},"required":["id","work","recording_artists"]}
artist.json :
{"$schema":"http://json-schema.org/draft-04/schema#","title":"Schema for an artist","type":"object","properties":{"id":{"type":"number"},"name":{"type":"string"},"functions":{"type":"array","items":{"type":"string"}}},"required":["id","name","functions"]}
And this is my error :
Connected to pydev debugger (build 181.5281.24)
Traceback (most recent call last):
File "C:\Python\lib\site-packages\proxytypes.py", line 207, in __subject__
return self.cache
File "C:\Python\lib\site-packages\proxytypes.py", line 131, in __getattribute__
return _oga(self, attr)
AttributeError: 'JsonRef' object has no attribute 'cache'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python\lib\site-packages\jsonref.py", line 163, in callback
base_doc = self.loader(uri)
<MORE>
python version : 3.6.5
windows 7
Ide : intellijIdea
Can somebody help me?
Thank you
I am not sure why, but on Windows, the file:// needs an extra /. So the following change should do the trick
base_uri = 'file:///{}/'.format(base_path)
Arrived at this answer from a solution posted for a related issue in json schema

Php json array into Python3

I have a php script that outputs a json array that looks like this...
[{"year":"2016","Month":"Apr","the_days":"16, 29, 30"},
{"year":"2016","Month":"May","the_days":"13, 27"},
{"year":"2016","Month":"Jun","the_days":"10, 11, 24"},
{"year":"2016","Month":"Jul","the_days":"08, 22, 23"},
{"year":"2016","Month":"Aug","the_days":"06, 20"},
{"year":"2016","Month":"Sep","the_days":"02, 03, 16, 17, 30"},
{"year":"2016","Month":"Oct","the_days":"01, 14, 15, 29"},
{"year":"2016","Month":"Nov","the_days":"25"},
{"year":"2016","Month":"Dec","the_days":"09, 10, 23, 24"}]
I'm trying to put together some Python that will (eventually) output something like....
Apr: 16, 29, 30
May: 13, 27
//etc
...but I'm not having any luck pulling the array out.
This is code that I'm using in Python3 (that I've pulled together from other Stack questions that I've searched for).
import urllib.request
import json
response = urllib.request.urlopen('http://www.captainobviousobviously.co.uk/private/Apijson.php')
content = response.read()
data = json.load(content.decode('utf-8'))
print(data)
This is the error that I'm getting...
Traceback (most recent call last):
File "/home/pi/Python/availableDates.py", line 6, in <module>
data = json.load(content.decode('utf-8'))
File "/usr/lib/python3.4/json/__init__.py", line 265, in load
return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'
I'm not really sure how to fix it.
Replace
data = json.load(content.decode('utf-8'))
with
data = json.loads(content.decode('utf-8'))
'load' is for files and 'loads' for strings.
Refer What is the difference between json.dumps and json.load?.
As for the code for your problem
for i in data:
print (str(i['Month'])+":"+str(i['the_days']))
Use json.loads instead. load is for loading from a stream, such as a file, whereas loads loads from a string.
data = json.loads(content.decode('utf-8'))
From the Python documentation:
json.load
Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table.
A string isn't a "file-like object", which is why you get your error - the JSON is trying to call .read on the string, but that doesn't exist.
You need to use json.loads(<json str>). If you want you can do the following
content = response.read().decode()
data = json.loads(content)
for d in data:
print(d["Month"], d["the_days"], sep=":")