I was trying to check if a string is JSON or not. If a string is not JSON string, I am trying to split the string (based on delim ":"). But it is throwing json.decoder.JSONDecodeError. I must be doing some silly mistake. But unable to figure out the issue.
Below is the simple program.
import json
str = "SIP/2.0 200"
try:
json.loads(str)
except ValueError as err:
substr = str.split((':', 1))
Below is the error
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/lib64/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/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)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
TypeError: must be str or None, not tuple
If I just print the string without splitting, it is working fine as below.
import json
str = "SIP/2.0 200"
try:
json.loads(str)
except ValueError as err:
print(str)
print(type(str))
O/P:
SIP/2.0 200
<class 'str'>
Not sure why I am getting this error. I might be doing some simple mistake. But unable to figure out the issue. Can anyone please help me to understand why splitting is failing.
Related
For a couple of days i've been trying to learn how to use JSON in python, but even if i copy everything from tutorials it still won't load.
import json
data = '''
{
"people":[
{
"name": "veljko",
"age":"20",
"email": veljkov02#gail.com,
"educated": "true"
} ,
{
"name":"aleksandar",
"age":"24",
"email":"marko99#gmail.com",
"educated":"false"
}
]
}
'''
men = json.loads(data)
print(men)
(Ignore the random words used in code, it's just how i learn)
It just keeps giving the same error messages, i've tried with the most simple JSON but it's still the same.
Traceback (most recent call last):
File "C:\Users\*********\Desktop\code3\json.py", line 21, in <module>
men = json.loads(data)
File "C:\Users\************\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\*************\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode.
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\************\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 7 column 14 (char 75)
Process finished with exit code 1
Please help, i'm a begginer and am not sure how to solve this problem.
You are missing quotes around veljkov02#gail.com. You need to change it to "veljkov02#gail.com", so that it is interpreted as a string. The exception tells you which line and character the error is at, so double check that line when you get errors like these.
I'd like to download a YAML file from Gitlab using Python requests. I'm almost there, but I havent quite got to the cigar stage.
I am doing the following :-
GITLAB_FILE ="https://my_url/api/v4/projects/my_id/repository/files/path_and_filename.yaml/raw?ref=master&private_token=mytoken"
g=requests.request("GET", GITLAB_FILE, verify=False)
print(g.json())
Now, it all works in as much as I can get to the file ok, but when it comes to accessing the data the print(g.json()) throws an error, but then continues to print out the file contents as I'd hoped. The error is :-
Traceback (most recent call last):
File "/home/myproj/edm/lib/python3.7/site-packages/requests/models.py", line 910, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/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)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./http_test.py", line 73, in <module>
print (g.json())
File "/home/myproj/edm/lib/python3.7/site-packages/requests/models.py", line 917, in json
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: [Errno Expecting value]
Once this is printed, it then proceeds to print out the contents of my yaml file correctly.
I suspect its something to do with the
print(g.json())
expecting a json format, and encountering a yaml file?
Any pointers as to how I can get the file contents error free would be helpful.
I've answered my own question.
Quite simply instead of
print(g.json())
I used
print(g.text)
Which did exactly what it said on the tin.
Im getting the error whenever i try to run this code in visual studio code.
Image of code
Error message:
Traceback (most recent call last):
File "c:\Users\climia1\Downloads\hangman.py", line 3, in <module>
r = requests.get('https://api.hypixel.net/skyblock/bazaar?key=29d9ecf6-71bb-49b1-b931-e0ed5f00f31d').json()
File "C:\Users\climia1\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\climia1\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\climia1\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\climia1\AppData\Local\Programs\Python\Python37\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)
[Done] exited with code=1 in 18.946 seconds
it displays the same error on repl.it but it goes away after one run. with visual studio it stays. any help?
Your json file must be empty or isn't formatted properly
if you are reading or writing to a empty Json file make sure it contains {}
if you are writing or reading a json file with lot of data make sure all the tags are closed
i have this code here:
import json
with open("pass_file.txt", "r") as file:
password = json.loads(file.read())
it calls this error:
Traceback (most recent call last):
File "testdoc.py", line 9, in <module>
print(json.loads(file.read()))
File "C:\Program Files\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Program Files\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Program Files\Python37\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 dont know why this is happening because i have the same code on another file just with different variable name and file name and it works file. I did notice another similar question about a similar error but it didnt answer my question.
Thanks in advance :)
What is the content of you pass_file.txt ? The python code use json.loads so it expect JSON formated content in the pass_file.txt
For example for a string, the content of this file will be "hello world"
If you don't put quotes, the JSON parsing process will fail.
I am trying to get started writing a Groupme bot using Groupy.
There have been a few related posts to this one, but they seemed a bit more technically challenging of issues, the solutions didn't seem efficient, and none of them solved the issues I'm having.
Here is the code I have so far:
import groupy
token = "{My Token}"
from groupy.client import Client
client = Client.from_token(token)
groups = list(client.groups.list_all())
for group in groups:
print(group)
Firstly, I don't believe this is related but, in eclipse it is giving a warning that groupy is an unused import, even though it seems to me that that is not so.
More importantly, the strange part about the issues I'm having is that the error messages change without any edits to the above code.
Here is an error message that I've gotten:
In each of these error messages, I've edited the beginning of the file locations... because I'm paranoid
Traceback (most recent call last):
File "\Projects\Eclipse\eclipse-workspace\Gort's Cousin\groupme_bot.py", line 15, in <module>
<Group(name='One of my group's names')>
<Group(name='Another one of my group's names')>
print(group.name)
File "\Python\Python37-32\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 27-28: character maps to <undefined>
So, this time the system actually returns a couple groups I am in. But then calls an exception because of a unicode error of sorts.
Without changing any code, I also get this error:
Traceback (most recent call last):
File "\Python\Python37-32\lib\site-packages\groupy\session.py", line 49, in data
return self.json()['response']
File "\Python\Python37-32\lib\site-packages\requests\models.py", line 808, in json
return complexjson.loads(self.text, **kwargs)
File "\Python\Python37-32\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "\Python\Python37-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "\Python\Python37-32\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 60865 (char 60864)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "\Eclipse\eclipse-workspace\Gort's Cousin\groupme_bot.py", line 10, in <module>
groups = list(client.groups.list_all())
File "\Python\Python37-32\lib\site-packages\groupy\pagers.py", line 61, in autopage
self.items = self.fetch_next()
File "\Python\Python37-32\lib\site-packages\groupy\pagers.py", line 51, in fetch_next
return self.fetch()
File "\Python\Python37-32\lib\site-packages\groupy\pagers.py", line 42, in fetch
return self.endpoint(**self.params)
File "\Python\Python37-32\lib\site-packages\groupy\api\groups.py", line 21, in _raw_list
return [Group(self, **group) for group in response.data]
File "\Python\Python37-32\lib\site-packages\groupy\session.py", line 51, in data
raise exceptions.InvalidJsonError(self._resp) from e
groupy.exceptions.InvalidJsonError: The JSON was incomplete/invalid
I am most likely incorrect, but it seems to me that there is some issue with the way groupy is aggregating the groups, and/or how I've set up my project to handle those calls.
Any help with this issue would be awesome.
I can also add some code from the groupy library if that becomes necessary.
TLDR: Getting a "UnicodeEncodeError" error using Groupy to write a groupme bot in Python
Solved:
It was an issue where group names with emojis were not playing nice with the Cp1252 encoding I have as a global setting in eclipse. I changed the run configuration of the file to encode to UTF-16BE. The emojis don't print correctly to the console, but all of the groups are printed with no errors.