So I was making a poll/voting system for fun using JSON, and I encountered this error when I was coding it:
Traceback (most recent call last):
File "C:\Users\ooich\PycharmProjects\16dec2022\main.py", line 48, in <module>
poll()
File "C:\Users\ooich\PycharmProjects\16dec2022\main.py", line 32, in poll
fp = json.load(f)
File "C:\Python310\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Python310\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Python310\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\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 1 column 1 (char 0)
I don't really understand 100% of what it means, given I have not touched code for over ~6 months.
Here's my code:
import json
def poll():
with open("poll.json", "r") as f:
fp = json.load(f)
le = fp.keys()
print(f"What would you like to vote?\n {le}")
i = input("Please write: ")
if fp.get(i) is None:
print("Key not found.")
return False
with open("poll.json", "w") as fe:
fep = json.load(fe)
fep[i] += 1
json.dump(fep, fe)
print("Voted!")
return True
poll()
Please do let me know if I missed something or you know how to solve it. Thanks.
I am guessing your json file is empty the same error as you when my json fill "poll.json" is empty.
with this json
poll.json
{"plop": 0}
and this python
import json
def poll():
with open("poll.json", "r") as f:
fp = json.load(f)
le = fp.keys()
print(f"What would you like to vote?\n {le}")
i = input("Please write: ")
if fp.get(i) is None:
print("Key not found.")
return False
with open("poll.json", "w") as f:
fp[i] += 1
json.dump(fp, f)
print("Voted!")
return True
poll()
result for ok
What would you like to vote?
dict_keys(['plop'])
Please write: plop
Voted!
result if no key present in json
What would you like to vote?
dict_keys(['plop'])
Please write: not
Key not found.
Related
Im learning how to update, write and read json files in python.
When I update my json file with exception handling it gives an error:
Exception in Tkinter callback Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/tkinter/__init__.py",
line 1921, in __call__
return self.func(*args) File "/Users/montekkundan/Downloads/coding/python/password-manager/main.py",
line 53, in save
data = json.load(data_file) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/__init__.py",
line 293, in load
return loads(fp.read(), File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/__init__.py",
line 346, in loads
return _default_decoder.decode(s) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/json/decoder.py",
line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/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)
Process finished with exit code 0
python function:
def save():
website = website_entry.get()
email = email_entry.get()
password = password_entry.get()
new_data = {
website: {
"email": email,
"password": password,
}
}
if len(website) == 0 or len(password) == 0:
messagebox.showerror(title="Oops!", message="Please make sure you haven't left any fields empty.")
else:
try:
with open("data.json", "r") as data_file:
# Reading old data
data = json.load(data_file)
except FileNotFoundError:
with open("data.json", "w") as data_file:
json.dump(new_data, data_file, indent=4)
else:
# Updating old data with new data
data.update(new_data)
with open("data.json", "w") as data_file:
# Saving updated data
json.dump(data, data_file, indent=4)
finally:
website_entry.delete(0, END)
password_entry.delete(0, END)
Check what you have in file - it seems it is empty.
And empty file/string is uncorrect JSON and it raises error.
You should rather create new empty dict data when it can't find file or it has problem to read it.
try:
with open("data.json", "r") as data_file:
# Reading old data
data = json.load(data_file)
except FileNotFoundError:
print("Problem: FileNotFoundError")
data = dict()
except json.JSONDecodeError:
print("Problem: JSONDecodeError")
data = dict()
finally:
# --- always ---
data.update(new_data)
with open("data.json", "w") as data_file:
# Saving updated data
json.dump(data, data_file, indent=4)
website_entry.delete(0, END)
password_entry.delete(0, END)
Hello I am reading and save a dict of dicts in JSON format, but when I use the json load I get this error.I still need to figure out what problem is it, what's the problem there? Thank you!!
JSON example:
data = {'multiplayer.it': {'news1.it': (title,date), 'news2.it': (title,date)},
'site2.it':{'news2.it':(title,date), 'news3.it': (title,date)}}
#tasks.loop(minutes=30)
async def get_gamesnews():
sites = ['https://multiplayer.it/articoli/notizie/']
for site in sites:
async with aiohttp.ClientSession() as ses:
async with ses.get(site) as response:
if response.status == 200:
text = await response.text()
soup = BeautifulSoup(text, 'lxml')
if site == 'https://multiplayer.it/articoli/notizie/':
div_news = soup.find_all('div', class_='media-body')
for news in div_news:
titles = news.find_all('a', class_='text-decoration-none')
for title in titles:
title_news = title.text.strip()
link_news = 'https://multiplayer.it' + title['href']
with open('dictionary_news.json', 'r+') as f:
dict_news = json.load(f)
dictvalues_news = dict_news.get('multiplayer.it')
if link_news not in dictvalues_news:
date_news = datetime.date.today().strftime('%Y-%m-%d')
dict_news['multiplayer.it'][link_news] = (title_news, date_news)
print((title_news, link_news, date_news))
channel = client.get_channel(855220263917191228)
await channel.send(f'{title_news} {link_news}')
json.dump(dict_news, f)
That's how I create the json file:
import json
data = {'multiplayer.it': {}}
with open('dictionary_news.json', 'w') as fp:
json.dump(data, fp)
Traceback:
Unhandled exception in internal background task 'get_gamesnews'.
Traceback (most recent call last):
File "C:\Users\Thund\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\tasks\__init__.py", line 101, in _loop
await self.coro(*args, **kwargs)
File "C:\Users\Thund\Desktop\RepoBitbucket\DiscordBot\main.py", line 75, in get_gamesnews
dict_news = json.load(f)
File "C:\Users\Thund\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\Thund\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\Thund\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\Thund\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)
The problem is that you're running json.dump(), after which json.load() can't be executed any more without reopening the file (at least to my knowledge, there might be workarounds).
Also remember that "r+" open the file in append mode, so that code would probably cause other problems latter.
I would recommend changing the code like this:
with open('dictionary_news.json', 'r') as f:
dict_news = json.load(f)
for title in titles:
title_news = title.text.strip()
link_news = 'https://multiplayer.it' + title['href']
dictvalues_news = dict_news.get('multiplayer.it')
if link_news not in dictvalues_news:
date_news = datetime.date.today().strftime('%Y-%m-%d')
dict_news['multiplayer.it'][link_news] = (title_news, date_news)
print((title_news, link_news, date_news))
channel = client.get_channel(855220263917191228)
await channel.send(f'{title_news} {link_news}')
with open('dictionary_news.json', 'w') as f:
json.dump(dict_news, f)
Since json.dump() writes the entire json, you should use mode 'w' for writing to the file.
I have the following code snippet:
input = "You can check it out here. https://www.youtube.com/watch?v=Ay1gCPAUnxo&t=83s I'll send $20 in bitclout to the first 50 people that follow instructions at end of the video. This is revolutionary. Let's hope it works! <3Building it. What's up y'all"
def createJsonText(input):
input = r'{}'.format(input)
x = r'{ "text":"' + input + r'"}'
print(x)
# parse x as json
y = json.loads(x)
f = open("tone.json", "a")
f.write(str(y))
f.close()
When I execute the aforementioned code I get the following error:
File "hashtag-analyzer.py", line X, in readJson
createJsonText(input) File "hashtag-analyzer.py", line Y, in createJsonText
y = json.loads(x) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/init.py",
line 354, in loads
return _default_decoder.decode(s) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py",
line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py",
line 355, in raw_decode
obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 4194 (char 4193)
How to resolve this?
Expected output is a json file with name, "tone.json" and the following data inside:
{
"text": "You can check it out here. https://www.youtube.com/watch?v=Ay1gCPAUnxo&t=83s I'll send $20 in bitclout to the first 50 people that follow instructions at end of the video. This is revolutionary. Let's hope it works! <3Building it. What's up y'all"
}
You're going the wrong direction here, if you want to create JSON. You want dumps, not loads':
def createJsonText(txt):
x = {'text': txt}
y = json.dumps(x)
open('tone.json','w').write(y)
Your code had mode='a' for append, but a set of separate JSON lines is NOT a valid JSON file. If you want it to be a valid JSON file, you need the whole file to be one document.
Update
Alternatively:
def createJsonText(txt):
json.dump({'text':txt}, open('tone.json','w'))
def state_manager(self, action):
# Define initialized state, default values.
initialized_state = {'access_token': None,
'refresh_token': None,
'token_expires_at': 0,
'authorization_url': None,
'redirect_code': None,
'token_scope': '',
'loggedin': False}
dir_path = r"C:\Users\kevin\Desktop\TDClient"
filename = 'TDAmeritradeState.json'
file_path = os.path.join(dir_path, filename)
# if the state is initialized
if action == 'init':
self.state = initialized_state
# if allowed cache load the file
if self.config['cache_state'] and os.path.isfile(file_path):
with open(file_path, 'r') as fileHandle:
self.state.update(json.load(fileHandle))
# If not allowed cache delete file
elif not self.config['cache_state'] and os.path.isfile(file_path):
os.remove(file_path)
# save and cache allowed load file
elif action == 'save' and self.config['cache_state']:
with open(file_path, 'w') as fileHandle:
# Build JSON string using dictionary comprehension.
json_string = {key:self.state[key] for key in initialized_state}
json.dump(json_string, fileHandle)
Full Trace Back:
> File "C:\Users\kevin\Desktop\TDClient\TDApi.py", line 47, in __init__
> self.state_manager('init') File
> "C:\Users\kevin\Desktop\TDClient\TDApi.py", line 101, in state_manager
> self.state.update(json.load(fileHandle)) File
> "C:\Users\kevin\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py",
> line 293, in load return loads(fp.read(), File
> "C:\Users\kevin\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py",
> line 357, in loads return _default_decoder.decode(s) File
> "C:\Users\kevin\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py",
> line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end())
> File
> "C:\Users\kevin\AppData\Local\Programs\Python\Python38-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) Expecting value: line 1 column 1 (char 0)
Hello, I am receiving this error, when I place the file_path into my code. When I put anything else into the os.path.isfile(), no error occurs. But when I reference my directory to the json file I want to save it to, it returns this error.
The information I am receiving is from TDameritrade, and it is in json format I believe, I do not know what am I doing wrong, and im referencing the directory incorrectly?
Expecting value: line 1 column 1 (char 0) Expecting value: line 1 column 1 (char 0)
Seems it fails while trying to parse empty JSON
If you’ve pulled JSON data in from another program or have otherwise obtained a string of JSON formatted data in Python, deserialize that with loads() instead of load()
New to coding and running through the exercises in Python Crash Course version 2. One of the exercises involves creating a file called "remember_me.py" and as far as I can tell, I'm entering the code as it exists in the book almost verbatim, but getting an error:
"""Exercise for Python Crash Course."""
import json
#Load the username, if it has been stored previously.
#Otherwise, prompt for the username and store it.
filename = 'username.json'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
username = input("What is your name?\n")
with open(filename, 'w') as f:
json.dump(username, f)
print(f"We'll remember you when you come back, {username}!")
else:
print(f"Welcome back, {username}!")
Whenever I try to run it, I get the following traceback (I replaced the username with "me" here):
Traceback (most recent call last):
File "C:\Users\me\Desktop\python_work\remember_me.py", line 9, in <module>
username = json.load(f)
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\me\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\me\AppData\Local\Programs\Python\Python38-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)
Any ideas what I'm doing wrong? I've tried just starting from scratch and re-typing, but apparently I'm making the same error!
import json
filename = 'username.json'
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
username = input("What is your name? ")
with open(filename, 'w') as f:
json.dump(username, f)
print(f"We'll remember you when you come back, {username}!")
except json.decoder.JSONDecodeError: # This error is for when the json file is EMPTY.
username = input("What is your name? ")
with open(filename, 'w') as f:
json.dump(username, f)
print(f"We'll remember you when you come back, {username}!")
else:
print(f"Welcome back, {username}!")
def get_stored_number():
try:
with open(filename) as f:
username = json.load(f)
except FileNotFoundError:
return None
**except json.decoder.JSONDecodeError:
return None**
else:
return username
number()
Solve this problem adding except for blank file username.json