I am using Python Crash Course book by Eric Matthes and have a problem with my code from examples page 211. I am attempting to save multiple usenames in a json doc and then retrieve them if username is stored, but if its a new username I would like it to store and not retrieve, so that multiple usernames are stored.
I am receiving JSONDecodeError: Expecting value
import json
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("Username: ")
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("Username stored. Thanks " + username + "!")
else:
print("Welcome back " + username +"!" + " You receive a returning
customer discount.")
Traceback:
runfile('/home/jubal/ CrashCourse Python Notes/Chapter 10 CC/returning_user.py', wdir='/home/jubal/ CrashCourse Python Notes/Chapter 10 CC')
Traceback (most recent call last):
File "/home/jubal/ CrashCourse Python Notes/Chapter 10 CC/returning_user.py", line 7, in <module>
username = json.load(f_obj)
File "/home/jubal/anaconda3/lib/python3.7/json/__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/home/jubal/anaconda3/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/home/jubal/anaconda3/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/home/jubal/anaconda3/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
JSONDecodeError: Expecting value
Any help would be appreciated. Thanks for your time!
Related
I want to append the brightness 0 to all lamps in list to a empty json file.
def first_start(lamps:list):
for lamp in lamps:
dict = {"light": {lamp: {"brightness": 0}}}
with open("data.json", "r") as file:
data = json.load(file)
data.update(dict)
print(dict)
with open("data.json", 'w') as file:
json.dump(data, file)
Everytime I run this code, I get this error:
Traceback (most recent call last):
File "C:\Users\brend\PycharmProjects\Hue_Control\main.py", line 27, in <module>
first_start(lamps)
File "C:\Users\brend\PycharmProjects\Hue_Control\main.py", line 16, in first_start
data = json.load(file)
File "C:\Users\brend\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\brend\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\brend\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\brend\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)
Could somebody please help me, what im doing wrong?
Thank you :)
There is no such thing as an empty json file. If you have an empty file, then its not a json file.
You could ignore all the errors and assume that the file should contain "{}" and carry on:
def first_start(lamps:list):
for lamp in lamps:
upd = {"light": {lamp: {"brightness": 0}}}
data = {} # Empty dict just in case
try:
with open("data.json", "r") as file:
data = json.load(file)
except Exception:
print('Ignore errors with data.json')
data.update(upd)
with open("data.json", 'w') as file:
json.dump(data, file)
I'm run my code to extract required data from RNA central database based RNAcentral accession number.
Sometimes in the middle, the program stops and start showing this error:
Error Obtained
File "C:\Users\soura\Desktop\Thesis\Saurav Data\Data_Extraction_RNA_Central.py", line 53, in <module>
data = page.json()['results']
File "D:\programs\anaconda3\lib\site-packages\requests\models.py", line 900, in json
return complexjson.loads(self.text, **kwargs)
File "D:\programs\anaconda3\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "D:\programs\anaconda3\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "D:\programs\anaconda3\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
JSONDecodeError: Expecting value
This is the part of my code where I'm having an error
import requests
import time
ids = ['URS0000D57BCE', 'URS0000D57BCE', 'URS0000EEF870', 'URS00009C33DE']
for id in range(len(ids)):
# Accessing the database cross-reference url with exception handling and extracting info
page = ''
while page == '':
try:
page = requests.get('http://rnacentral.org/api/v1/rna/{}/xrefs.json'.format(ids[id]))
break
except:
print('Connection refused by the server at id {} and position {}'.format(ids[id], ids.index(ids[id])))
print('Lets me sleep for 5 seconds')
time.sleep(5)
continue
# Extracting json content from above url
data = page.json()['results']
Later I modified my code like this but still, I'm getting the same error:
I Changed page = '' to page = None
I thought since the error is for the None value of the page. I wrote a while loop in such a way until there is the None value of page, the code will re-run again and again.
import requests
import time
ids = ['URS0000D57BCE', 'URS0000D57BCE', 'URS0000EEF870', 'URS00009C33DE']
for id in range(len(ids)):
# Accessing the database cross-reference url with exception handling and extracting info
page = None
while page == None:
try:
page = requests.get('http://rnacentral.org/api/v1/rna/{}/xrefs.json'.format(ids[id]))
break
except:
print('Connection refused by the server at id {} and position {}'.format(ids[id], ids.index(ids[id])))
print('Lets me sleep for 5 seconds')
time.sleep(5)
continue
# Extracting json content from above url
data = page.json()['results']
Now, I'm getting this error:
Traceback (most recent call last):
File "Data_Extraction_RNA_Central.py", line 61, in <module>
data = page.json()['results']
File "C:\Users\soura\AppData\Local\Programs\Python\Python37\lib\site-packages\requests\models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\soura\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\soura\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\soura\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)
Please if anyone can help, it will be a great help for me. :-)
I'm running twitter_hashtag_frequency.py program on Pycharm with json file parameter and I have this error :
['C:/Users/HP/PycharmProjects/Bonzanini_Book_Exercises/twitter_hashtag_frequency.py', 'stream_.jsonl']
Traceback (most recent call last):
File "C:/Users/HP/PycharmProjects/Bonzanini_Book_Exercises/twitter_hashtag_frequency.py", line 17, in <module>
tweet = json.loads(line)
File "C:\Users\HP\Anaconda3\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\HP\Anaconda3\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\HP\Anaconda3\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1)
This is the code:
# Chap02-03/twitter_hashtag_frequency.py
import sys
from collections import Counter
import json
def get_hashtags(tweet):
entities = tweet.get('entities', {})
hashtags = entities.get('hashtags', [])
return [tag['text'].lower() for tag in hashtags]
if __name__ == '__main__':
print(sys.argv)
fname = sys.argv[1]
with open(fname, 'r') as f:
hashtags = Counter()
for line in f:
tweet = json.loads(line)
hashtags_in_tweet = get_hashtags(tweet)
hashtags.update(hashtags_in_tweet)
for tag, count in hashtags.most_common(20):
print("{}: {}".format(tag, count))
As you see in the screenshot the json file stream_.jsonlis in the same path with the program Pycharm running window
The windows of edit configuration sounds like good this is the screenshoot Run debug configurations screenshot
The json file file is an output of streaming tweets of 4629 lines. I would have your help, thank you.
import json
import pandas as pd
import collections
import os
path = '/home/vinay/hdfs/kafka-logs/event_tablenames.txt'
file_read = '/home/vinay/hdfs/kafka-logs/hdfs_events/'
table_file = '/home/hdfs/vinay/kafka-logs/events_tables/'
con_json = '/home/vinay/hdfs/kafka-logs/json_to_txt/'
os.chdir(file_read)
files=os.listdir('.')
for file in files:
line = file.split('.')[0]
with open(file ,'r') as f:
print (json.load(f))
data = json.load(f)
key = data[line]
od = collections.OrderedDict(sorted(key.items()))
df = pd.DataFrame(list(od.items()), columns=['col_name', 'type'])
df['col_name'].to_csv(con_json + line + '.txt',sep='\t', index=False, header=False)
Below is a full traceback:
Traceback (most recent call last):
File "events_match_hdfs.py", line 29, in <module>
data = json.load(f)
File "/home/vinay/anaconda3/lib/python3.5/json/__init__.py", line 268, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/home/vinay/anaconda3/lib/python3.5/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/home/vinay/anaconda3/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/home/vinay/anaconda3/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)
You didn't show the full traceback from the error in your question, so this is a just a guess.
I think the problem is because you're trying to do json.load(f) twice on the same file. The first one consumes the entire file, so the second one fail. Try changing the first couple of lines after opening the file to this:
with open(file ,'r') as f:
data = json.load(f)
print(data)
Json filename was not proper,and the size was zero.Due to that it was
throwing error.
Thanks all for your inputs.
I am new to programming and I created a son program that stores your name, than the items in your list.
import json
list_ = []
filename = 'acco.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What is your name? ")
while True:
list_items = input("What is the item you want to add? q to quit")
if list_items == 'q':
break
list_.append(list_items)
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("These is your list of items:")
print(list_)
print("We'll remember you when you come back, " + username + "!")
json.dump(list_items, f_obj)
else:
print("Welcome back, " + username + "!")
print("Here are the items of your list:")
print(_list)
However, an error keeps showing up when I run the program. The error says that there is an error in line 8, the line of code where it says
username = json.load(f_obj)
This is the exact error
Traceback (most recent call last):
File "/Users/dgranulo/Documents/rememberme.py", line 8, in <module>
username = json.load(f_obj)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 8 (char 7)
If anyone can help that would be greatly appreciated,
Thanks,
You're serializing objects one by one. A str and a list. Do it once in a collection like a list or dict.
This one works;
>>> print(json.loads('"a"'))
a
But this one a str and a list is an error;
>>> json.loads('"a"[1]')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.6/json/decoder.py", line 342, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 4 (char 3)
Write to the file with a dict;
with open(filename, 'w') as f_obj:
# json.dump(username, f_obj)
print("These is your list of items:")
print(list_)
print("We'll remember you when you come back, " + username + "!")
# json.dump(list_items, f_obj)
# dump a dict
json.dump({'username': username, 'items': list_}, f_obj)
Now json.load will return a dict with keys username and items.