Issue in Discord.py while linking JSON - json

I'm having an issue in linking Discord.py with JSON. Here's my code:
#client.event
async def on_guild_join(guild):
role = discord.utils.get(guild.roles, name="Muted")
with open("muted_roles.json", "r") as f:
muted_roles = json.load(f)
muted_roles[str(guild.id)] = str(role.id)
with open("muted_roles.json", "w") as f:
json.dump(muted_roles, f, indent=4)
Here's my error:
Ignoring exception in on_guild_join
Traceback (most recent call last):
File "C:\Users\angel\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\angel\Documents\python\Bots\dave\dave.py", line 59, in on_guild_join
muted_roles = json.load(f)
File "C:\Users\angel\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\angel\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\angel\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\angel\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I thank early for the assistance.

Your JSON file is empty you should fill it with {} and it will fix!

Related

Safely parsing nested json double quotes

The issue:
>>> import json
>>> json_str='{"message": "John said "come here!""}'
>>> json.loads(json_str)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ram/.pyenv/versions/3.9.6/lib/python3.9/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/Users/ram/.pyenv/versions/3.9.6/lib/python3.9/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/ram/.pyenv/versions/3.9.6/lib/python3.9/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 25 (char 24)
Then I attempted to escape the double-quotes. Like so:
>>> json_str='{"message": "John said \"come here!\""}'
>>> json.loads(json_str)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ram/.pyenv/versions/3.9.6/lib/python3.9/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/Users/ram/.pyenv/versions/3.9.6/lib/python3.9/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/ram/.pyenv/versions/3.9.6/lib/python3.9/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 25 (char 24)
The following works though:
>>> json_str='{"message": "John said \'come here!\'"}'
>>> json.loads(json_str)
{'message': "John said 'come here!'"}
What am I doing wrong? Is it possible to flag the json library to be more forgiving (helps me leave json parsing to the json library)?
PS: Following the answer here, I attempted the following:
>>> data=json.dumps('{"message":"John said "hello!""}')
>>> print(data)
"{\"message\":\"John said \"hello!\"\"}"
>>> dict = json.loads(data)
>>> print(dict)
{"message":"John said "hello!""}
>>> print(dict['message'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
>>> print(dict[0])
{
The last json.loads is returning a string instead of dict. But the correctly escaped quotes in data did sound promising.
You can simply use either a raw string or double backslashes so that you both escape the backslashes in python as well as in the json string so that json.loads can see the backslashes.
>>> json.loads(r'{"message": "John said \"come here!\""}')
{'message': 'John said "come here!"'}
>>> json.loads('{"message": "John said \\"come here!\\""}')
{'message': 'John said "come here!"'}

Write the correct format of JSON to file using json.dumps() in Python 3

Let say I have a simple dictionary as below:
a = {'animal' : 'fish', 'fruit' : 'apple','vehicle' : 'car'}
I wish to convert a into JSON and write to a file. If I used json.dumps() as below:
b = jason.dumps(a)
with open('output.json', 'w') as f:
f.write(pprint.pformat(b))
The content of the JSON file output.json became:
'{"animal": "fish", "fruit": "apple", "vehicle": "car"}'
What I wish to actually have (in the file) is without quote as below:
{"animal": "fish", "fruit": "apple", "vehicle": "car"}
What is the right way to code it so that I can get the desired output?
Thanks in advance.
[EDIT]: The reason why I need the desired output in file is because I received the error below when I loaded the file.
>>> with open("output.json") as f:
... data = json.load(f)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/Users/louis.kok/Analyses/devel/anaconda3/lib/python3.7/json/__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/Users/louis.kok/Analyses/devel/anaconda3/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/Users/louis.kok/Analyses/devel/anaconda3/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/louis.kok/Analyses/devel/anaconda3/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Import json library
import json
Save your file properly using json.dump
with open('output.json', 'w') as f:
json.dump(a, f)
Read it using json.load
with open("output.json") as f:
data = json.load(f)
Try this:
with open('task.json', 'w') as f:
s = json.dumps(mydict, indent=2)
f.write('%s\n' % (s))

json decod error when using POST in chalice

When I try to use app.current_request.json_body in chalice I get a decode error:
Traceback (most recent call last): File "/var/task/chalice/app.py",
line 659, in _get_view_function_response
response = view_function(**function_args) File "/var/task/app.py", line 34, in post_item
data = app.current_request.json_body File "/var/task/chalice/app.py", line 303, in json_body
self._json_body = json.loads(self.raw_body) File "/var/lang/lib/python3.6/json/init.py", line 354, in loads
return _default_decoder.decode(s) File "/var/lang/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/var/lang/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char
0)
It doesn't matter how simple the data is. Example: {"Company":"ABC"} or {}.
As can be seen in the following code in the API Gateway all I try to do is return the data that has been sent so I don't think this is the problem:
#app.route('/test', methods=['POST'], content_types=['application/json'], cors=cors_config)
def post_item(data):
data = app.current_request.json_body
return data
Does anyone know what I might have done wrong?
You must remove the data from the parameters of the function.
That is used for pass url parameters.
#app.route('/test', methods=['POST'], content_types=['application/json'], cors=cors_config)
def post_item():
data = app.current_request.json_body
return data

Error when using ipapi python API for getting geo location from IP

I am using ipapi to get geo location from IP. It works for most part but get the following error for some of the ip's I tried.
File " ...ipapi\ipapi.py", line 47, in location
return response.json()
ValueError: Expecting value: line 1 column 1 (char 0)
*** print_exc:
File "...\models.py", line 892, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Python34\lib\json\__init__.py", line 318, in loads
return _default_decoder.decode(s)
File "C:\Python34\lib\json\decoder.py", line 343, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python34\lib\json\decoder.py", line 361, in raw_decode
raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)
CODE:
(ip.location(ip=ip_address))
Any suggestions how to resolve this issue??
Thanks

How to Print list [] based JSON?

I am trying to print below json output using below script,
Json Sample:
[{"id":"56cd7e4d2d0edcace915e674","protocol":"https","hostName":"127.0.0.1","port":443,"serverName":"Site1","status":"connected","connected":true}]
Code i have used:
import Requests
response = requests.get("https://Site1/rest/settings/all-server-status",params={'serverId': '56cd7e4d2d0edcace915e674'}, verify=False)
json_data = json.loads(response.text)
When i am trying to print json_data i got below error,
Traceback (most recent call last):
File "<pyshell#116>", line 1, in <module>
json_data = json.loads(response.text)
File "C:\Python27\lib\json\__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
Please help me on this, Thanks in advance!!