Try Except Else not functioning - python

With the following code. Which iterates through a list of message ids and creates the http request and then appends to json. I am having problems with exceptions. The Try except Else doesn't seem to work.
import urllib3
import json
import csv
from progressbar import ProgressBar
import time
pbar = ProgressBar()
base_url = 'https://api.pipedrive.com/v1/mailbox/mailMessages/'
fields = {"include_body": "1", "api_token": "token"}
json_arr = []
http = urllib3.PoolManager()
with open('msgid.csv', newline='') as csvfile:
for x in pbar(csv.reader(csvfile, delimiter=' ', quotechar='|')):
while True:
try:
r = http.request('GET', base_url + "".join(x), fields=fields)
break
except Exception:
time.sleep(1)
mails = json.loads(r.data.decode('utf-8'))
json_arr.append(mails)
with open('JDATA.json', 'w', encoding="utf-8") as outfile:
json.dump(json_arr, outfile)
I literally want it to skip over an error and move on to the next iteration.
but i constantly get this thrown up at random iteration numbers:
Traceback (most recent call last):
File "API.py", line 23, in <module>
mails = json.loads(r.data.decode('utf-8'))
File "C:\Users\Robert Millard\AppData\Local\Programs\Python\Python36- 32\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Users\Robert Millard\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Robert Millard\AppData\Local\Programs\Python\Python36-32\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)

Related

JSONDecodeErrror while trying to decide JSON from file

I am trying to create a very simple blockchain with Python.
import json
import os
import hashlib
blockchain_dir = os.curdir + "/blockchain/"
The code can save blocks, but if want to use the check_integrity function I get an JSONDecodeError:
def get_hash(filename):
file = open(blockchain_dir + filename, "rb").read()
return hashlib.md5(file).hexdigest()
def get_files():
files = os.listdir(blockchain_dir)
return sorted([int(i) for i in files])
def check_integrity():
files = get_files()
results = []
for file in files[:1]:
f = open(blockchain_dir + str(file))
h = json.load(f)['hash']
prev_file = str(file - 1)
actual_hash = get_hash(prev_file)
if h == actual_hash:
res = 'OK'
else:
res = 'Corrupted'
results.append({'block': prev_file, 'result': res})
return results
def write_block(name, amount, to_whom, prev_hash=''):
files = get_files()
prev_file = files[-1]
file_name = str(prev_file + 1)
prev_hash = get_hash(str(prev_file))
data = {"name": name,
"amount": amount,
"to_whom": to_whom,
"hash": prev_hash}
with open(blockchain_dir + file_name, "w") as file:
json.dump(data, file, indent=4, ensure_ascii=False)
def main():
write_block("Friend", 120, "Me")
print(check_integrity())
if __name__ == "__main__":
main()
Traceback (most recent call last):
File "/Python/blockchain/block.py", line 67, in <module>
main()
File "/Python/blockchain/block.py", line 64, in main
print(check_integrity())
File "/Python/blockchain/block.py", line 31, in check_integrity
h = json.load(f)['hash'] # method load - take object and return json object, hash - it is key in the block file, we get hash from the block file and compare it with hash that we get after function get_hash
File "/usr/lib/python3.9/json/__init__.py", line 293, in load
return loads(fp.read(),
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)
What is the problem, and how can I fix it?
The issue is that the json file you're trying to parse is empty.I'm not familiar with any method to automatically check if a json file is empty, apart from checking for such an occurrence manually. You can manually check and confirm whether a json file is empty by adding a try-except statement in your check integrity function i.e:
try:
h = json.load(f)['hash']
except KeyError:
...
The keyerror catches a scenario where the "hash" key is empty therefore suggesting the data your trying to access doesn't exist.

JSONDecodeError expecting value: line 1 column 1

I've looked for similar questions, but I couldn't find anything what can help me. When i execute this code (which should work) I get "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)"
TOKEN = '_EXAMPLE_TOKEN_'
def getPagedData(start,size):
url = 'http://EXAMPLE_URL'.format(start, size)
response = requests.get(url, headers={'token': TOKEN}, verify=False)
return response
def getDataInBatches():
start = 0
size = 1000
allData = []
data = getPagedData(start, size)
allData.extend(data.json()['data'])
total = data.json()['count']
for i in range(1, round(total/size) + 1):
print(allData[len(allData) - 1])
allData.extend(getPagedData(i * size, size).json()['data'])
return allData
print(getDataInBatches())
Here full traceback:
Traceback (most recent call last):
File "C:/Users/userxy/Documents/workProject/API/Get_Information.py", line 30, in <module>
print(getDataInBatches())
File "C:/Users/userxy/Documents/workProject/API/Get_Information.py", line 23, in getDataInBatches
allData.extend(data.json()['data'])
File "C:\Users\userxy\Anaconda3\lib\site-packages\requests\models.py", line 898, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\userxy\Anaconda3\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\userxy\Anaconda3\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\userxy\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 1 column 1 (char 0)
What can it be?
Make sure the response is in json format. The standard way to ensure the response is in json format is to add a headers={'Content-Type': 'application/json'}
But to be sure, check the documentation of an API you're accessing.

JSON decode error since I switched from macOS to Windows

I have a Python file that worked perfectly on my macbook.
Once I moved it to window, for some reason it gave me new error.
this is the errors im getting:
Traceback (most recent call last):
File "C:/Users/chadi/PycharmProjects/untitled4/main.py", line 3, in <module>
from main_controller import Ui_MainController
File "C:\Users\chadi\PycharmProjects\untitled4\main_controller.py", line 6, in <module>
from get_companies import load_companies
File "C:\Users\chadi\PycharmProjects\untitled4\get_companies.py", line 10, in <module>
json_read('convertcsv.json')
File "C:\Users\chadi\PycharmProjects\untitled4\get_companies.py", line 8, in json_read
data = (json.load(f_in))
File "C:\Users\chadi\anaconda3\envs\untitled4\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\chadi\anaconda3\envs\untitled4\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\chadi\anaconda3\envs\untitled4\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\chadi\anaconda3\envs\untitled4\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)
Process finished with exit code 1
this is all the parts where i load a JSON file:
def json_read(filename):
with open(filename) as f_in:
global data
data = (json.load(f_in))
json_read('convertcsv.json')
def mark_employee_unavailability(service,employee,reason,start_date,end_date):
with open('info_inspecteurs.json') as json_file:
data = json.load(json_file)
for i in range(len(data)):
if data[i]['n_inspecteur'] == employee:
event_email = data[i]['email_inspecteur']
break
def json_read(filename):
with open(filename) as f_in:
global data
data = (json.load(f_in))
def get_employee_info(n_inspecteur):
json_read('info_inspecteurs.json')
value = list(filter(lambda x: x["n_inspecteur"] == n_inspecteur, data))[0]
if len(value) > 0:
print(value['ad_inspecteur'], "\n", value['email_inspecteur'])
return (value['ad_inspecteur'],value['email_inspecteur'])
print("no record found")
return None
def load_employees_from_info_inspecteurs():
json_read('info_inspecteurs.json')
employees=[]
for company in data:
employees.append(company['n_inspecteur'])
return employees
I don't know where it came from, or maybe is the new environement I used on Windows? I used anaconda. Does it change anything? I was on VENV on my macOS.
Thank you for your help
The error
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
may just mean that there's no data being read from the target file at all, so json isn't finding any data to parse.
You might troubleshoot by trying to just read the file from that point in your script into a string - if it fails, the problem may be in python execution current directory / relative file path, rather than in the json parsing.
with open ("convertcsv.json", "r") as checkFile:
checkData = checkFile.read()
# print out length or contents of checkData or sim.

Creating dataframe from json not always working

I'm trying to run this code to create a data frame from a JSON link. Sometimes, the code will run. Other times, I will get an error message (below). I'm not sure why this occurs, even though the code is the same.
import requests
import json
url = "http://stats.nba.com/stats/leaguedashplayerstats?College=&Conference=&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment=&Height=&LastNGames=0&LeagueID=00&Location=&MeasureType=Advanced&Month=0&OpponentTeamID=0&Outcome=&PORound=0&PaceAdjust=N&PerMode=Totals&Period=0&PlayerExperience=&PlayerPosition=&PlusMinus=N&Rank=N&Season=2016-17&SeasonSegment=&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=&VsDivision=&Weight="
jd = requests.get(url).json()
df = []
for item in requests.get(url).json()['resultSets']:
print("got here")
row_df = []
for row in item['rowSet']:
row_df.append(str(row).strip('[]'))
df.append("\n")
df.append(row_df)
print(df)
Error Message:
Traceback (most recent call last):
File "/Users/K/PycharmProjects/mousefun/fun", line 8, in <module>
jd = requests.get(url).json()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/requests/models.py", line 812, in json return complexjson.loads(self.text, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/__init__.py", line 318, in loads return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/decoder.py", line 343, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/json/decoder.py", line 361, in raw_decode raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)
Change your request logic to this and try again:
r = requests.get(url)
r.raise_for_status()
df = []
for item in r.json()["resultSets"]:
# ...
r.raise_for_status() will raise if the status is not OK .
Also, this does not do the request two times like your code does.

reading a json file in python

hi I want to read a JSON file in python and any kind of syntax that i use i receive an error and i don't know what to do the code :
import urllib
import pprint
import json
import re
import requests
import pprint
with open('synsets.json' , encoding = 'utf-8') as json_data:
d = json.loads(json_data.read())
json_data.close()
pprint(d)
the error :
Traceback (most recent call last):
File "D:\markaz\wikiomega\code1.py", line 13, in <module>
d = json.loads(json_data.read())
File "C:\Users\BehnaM1\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "C:\Users\BehnaM1\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\BehnaM1\AppData\Local\Programs\Python\Python35-32\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)
[Finished in 0.7s with exit code 1]

Categories

Resources