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)
Related
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.
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'm making an API call and I'm getting an None value as I loop through my file.
I would place my csv in here, but it's over 100k records.
My code:
import csv
import xml.etree.ElementTree as ET
import xml.dom.minidom
import requests
import json
import pandas as pd
from pandas.io.json import json_normalize
#Storing results
api_results = []
error_results = []
none_results = []
print('Starting XML loop')
with open("C:/Users/template_v2.csv") as f:
reader = csv.DictReader(f)
# WRITING TO XML NODES
for i, row in enumerate(reader, start=1):
# INITIALIZING XML FILE
root = ET.Element('cbcalc')
icdNode = ET.SubElement(root, "icdcodes")
#handling first level ICD codes
for code in row['D'].split('~'):
ET.SubElement(icdNode, "code").text = code
#handling Client ID, state, country, age, job class and output
ET.SubElement(root, "clientid").text = row['CLAIM_NUM']
ET.SubElement(root, "state").text = row['BEN_ST']
ET.SubElement(root, "country").text = "US"
ET.SubElement(root, "age").text = row['AGE']
ET.SubElement(root, "jobclass").text = "1"
ET.SubElement(root, "fulloutput").text ="Y"
#handling the cfactors:
cfNode = ET.SubElement(root, "cfactors")
for k in ['legalrep', 'depression', 'diabetes',
'hypertension', 'obesity', 'smoker', 'subabuse']:
ET.SubElement(cfNode, k.lower()).text = str(row[k])
psNode = ET.SubElement(root, "prosummary")
psicdNode = ET.SubElement(psNode, "icd")
for code in row['P'].split('~'):
ET.SubElement(psNode, "code").text = code
psndcNode = ET.SubElement(psNode, "ndc")
for code in row['NDC_codes'].split('~'):
ET.SubElement(psNode, "code").text = code
cptNode = ET.SubElement(psNode, "cpt")
for code in row['CPT_codes'].split('~'):
ET.SubElement(cptNode, "code").text = code
ET.SubElement(psNode, "hcpcs")
doc = ET.tostring(root, method='xml', encoding="UTF-8")
response = requests.post(target_url, data=doc, headers=login_details)
response_data = json.loads(response.text)
if type(response_data)==dict and 'error' in response_data.keys():
error_results.append(response_data)
elif response_data == None or response_data == '':
none_results.append(response_data)
else:
api_results.append(response_data)
print('creating dataframe')
strategic_df = pd.json_normalize(api_results)
print("Writing out csv file")
strategic_df.to_csv(r'C:\Users\_dataframe2.csv', index = False, header=True)
Here is my error message:
Traceback (most recent call last):
File "c:\Users\Python\sc_ras_api.py", line 66, in <module>
response_data = json.loads(response.text)
File "C:\Users\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\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\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)
What did I break and how do I fix it?
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