So I got the JSONDecodeError in json.load() while everything seems to be right.
My code:
def write(name: str, text):
try:
with open("C:/Users/FlexGames/Desktop/Programming/Discord Bot/New Bot/banned.json", "w") as bannedload:
bannedjson[name] = text
json.dump(bannedjson, bannedload)
except NameError:
_load(jsonfile)
return write(name, text, jsonfile)
def _load():
global bannedjson, bannedload
with open("C:/Users/FlexGames/Desktop/Programming/Discord Bot/New Bot/banned.json", "r") as bannedload:
bannedjson = json.load(bannedload)
JSON File:
{
"banned": []
}
Error Output:
Traceback (most recent call last):
File "C:\Users\Try Me Btch\AppData\Local\Programs\Python\lib\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "C:\Users\FlexGames\Desktop\Programming\Discord Bot\New Bot\main.py", line 77, in on_message
await ban.user(message)
File "C:\Users\FlexGames\Desktop\Programming\Discord Bot\New Bot\New_Functions\ban.py", line 11, in user
jsonhandle.write("banned", int(content[1]))
File "C:\Users\FlexGames\Desktop\Programming\Discord Bot\New Bot\Functions\jsonhandle.py", line 27, in write
_load(jsonfile)
File "C:\Users\FlexGames\Desktop\Programming\Discord Bot\New Bot\Functions\jsonhandle.py", line 42, in _load
bannedjson = json.load(bannedload)
File "C:\Users\Try Me Btch\AppData\Local\Programs\Python\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\Try Me Btch\AppData\Local\Programs\Python\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\Try Me Btch\AppData\Local\Programs\Python\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Try Me Btch\AppData\Local\Programs\Python\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)
Most "solutions" I found in the internet were faults like .loads() or large and lower case faults or something like this but not this error in this context
So the solution was like SiHa said something was broken with the path, I don't know what exactly but as I removed the whole path but the file it worked 🤷♂️
Related
Following code was used in Thonny (offline) IDE and it works fine. But when I use the same code in trinket it gives me an error. What could be the reason?
def compare_prices(product_laughs,product_glomark):
html_lau=requests.get(product_laughs).content
html_glo=requests.get(product_glomark).content #get the content of the site
soup_lau=BeautifulSoup(html_lau,'html.parser')
soup_glo=BeautifulSoup(html_glo,'html.parser')
glo_products=soup_glo.find("script", type="application/ld+json")
glomark_content=glo_products.text #glomark product list
print(glomark_content)
productList=json.loads(glomark_content)
This last statement gives the following error
Traceback (most recent call last):
File "/tmp/sessions/96aa9a060805dc3c/main.py", line 4, in <module>
compare_prices(laughs_coconut,glomark_coconut)
File "/tmp/sessions/96aa9a060805dc3c/compare_prices.py", line 27, in compare_prices
productList=json.loads(glomark_content)
File "/usr/lib/python3.9/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.9/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.9/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 made a script with a friend, unluckily the script does not run smoothly. It fails at some point and gives the following error:
Traceback (most recent call last):
File "restClient.py", line 157, in <module>
loop.run_until_complete(task)
File "/usr/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
return future.result()
File "restClient.py", line 142, in func
available = client.getStockAmount(_product)
File "/root/brandcanyon/BrandCanyonApi/client.py", line 269, in getStockAmount
productId, productVariantId = self.findProductIdAndVariantId(product.name, product.size)
File "/root/brandcanyon/BrandCanyonApi/client.py", line 168, in findProductIdAndVariantId
product = self.getProductById(productId)
File "/root/brandcanyon/BrandCanyonApi/client.py", line 136, in getProductById
product = response.json()['data']
File "/usr/local/lib/python3.7/dist-packages/requests/models.py", line 900, 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)
The restClient.py File that the script is talking about is the following:
while True:
for product in page1:
for variant in product.attributes['variants']:
print(variant.attributes)
print(product.attributes['title'])
print(variant.attributes['option2'])
_product = Product(
name = product.attributes['title'],
size = variant.attributes['option2']
)
shopify.InventoryLevel.set(
location_id = location_id,
inventory_item_id = variant.inventory_item_id,
available = client.getStockAmount(_product)
)
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
if page1.has_next_page():
page1 = page1.next_page()
else:
break
print("Inventory Updated - Waiting 350 seconds for next Update")
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
await asyncio.sleep(20)
loop = asyncio.get_event_loop()
task = loop.create_task(func())
try:
loop.run_until_complete(task)
except asyncio.CancelledError:
pass
Do you know the error? Can you help me out?
Thank you so much!
I have a school schedule in my program, and when I use
import json
if choice == "Schedule":
with open("Schedule.json", "r") as schedule_file:
schedule_output = json.load(schedule_file)
schedule_choice = input('\nDo you want to exit or change the schedule?\n')
The problem comes up:
Traceback (most recent call last):
File "practice.py", line 92, in <module>
schedule_output = json.load(schedule_file)
File "C:\Users\Samwise\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\Samwise\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\Samwise\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Samwise\AppData\Local\Programs\Python\Python38\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 tried to change the encoding, but it didn't help me.
I'm trying to load a file to a variable, but I get the error json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) in whitelist = json.load(f), what am I doing wrong?
def load_whitelist():
global whitelist
wl = "C:/Users/Administrator/Desktop/Software/whitelist.json"
if os.path.isfile(wl):
with open(wl, mode='r') as f:
whitelist = json.load(f)
f.close()
print(whitelist)
def save_whitelist():
wl = "C:/Users/Administrator/Desktop/Software/whitelist.json"
if os.path.isfile(wl):
with open(wl, mode='w') as f:
json.dump(whitelist, f, sort_keys=False)
f.close()
Full Traceback:
Traceback (most recent call last):
File "PC200.py", line 970, in <module>
load_whitelist()
File "PC200.py", line 51, in load_whitelist
whitelist = json.load(f)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\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)
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000020022935828>
The JSON
[{"ignoresPlayerLimit": false, "name": "AndRKConnor8000","xuid":"2535435055474031"},{"ignoresPlayerLimit":false,"name":"ThePurplishGame","xuid":"2535461240132600"}]
Not really an answer but it cannot fit into a comment. With only the error message, it is impossible to know what happens. This error can be reproduced with an empty file, or with an incorrect encoding. Example simulating an empty file:
>>> import json
>>> import io
>>> fd = io.StringIO()
>>> wl = json.load(fd)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
wl = json.load(fd)
File "D:\Program Files (x86)\Python37-32\lib\json\__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "D:\Program Files (x86)\Python37-32\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "D:\Program Files (x86)\Python37-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "D:\Program Files (x86)\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 1 (char 0)
Example simulating an UTF16 encoded file read as Latin1:
>>> t = '''[{"ignoresPlayerLimit": false, "name": "AndRKConnor8000","xuid":"2535435055474031"},{"ignoresPlayerLimit":false,"name":"ThePurplishGame","xuid":"2535461240132600"}]'''
>>> tt = t.encode('utf16').decode('latin1')
>>> fd=io.StringIO(tt)
>>> wl = json.load(fd)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
wl = json.load(fd)
File "D:\Program Files (x86)\Python37-32\lib\json\__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "D:\Program Files (x86)\Python37-32\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "D:\Program Files (x86)\Python37-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "D:\Program Files (x86)\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 1 (char 0)
The only way to discriminate the problem is to read and print the content of the file:
with open(wl, mode='r') as f:
data = f.read() # read file conten
print(data) # display it as text
print([hex(ord(i)) for i in data]) # and as an hex dump
That way you will be sure of the way Python actually reads the file.
def load_whitelist():
global whitelist
wl = "C:/Users/Administrator/Desktop/Software/whitelist.json"
if os.path.isfile(wl):
with open(wl, mode='r') as f:
whitelist = json.load(f)
f.close()
def save_whitelist():
wl = "C:/Users/Administrator/Desktop/Software/whitelist.json"
print(whitelist)
with open(wl, mode='w') as f:
json.dump(whitelist, f, sort_keys=False)
f.close()
It seems like there was an error with saving the whitelist and it deleted the JSON contents, the code itself was ok (I removed the if os.path.isfile(wl): as it was unnecessary). Thank you all for trying to help!
for i in os.listdir("./saves/"):
path = './saves/' + i
if path.endswith(".json"):
with open(path, "r"):
config = json.loads(path)
ctime = config["Creation Time"]
Okay, this is the small code that's causing errors. I'm getting a json decoder error Here is the callback
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 1550, in __call__
return self.func(*args)
File "/Users/acrobat/PycharmProjects/Jan9coderun/TranslatorVCS/Quiz.py", line 318, in saveGame
config = json.loads(path)
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/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)
My saves folder is in the same working directory as my code and has one quiz.json, one notes.txt, and one __init__.py file.