Python Code:
import json
bankstatementjson = open('bankstatement_sept_20.json', 'r')
bankstatement = bankstatementjson.read()
bankstm = json.loads(bankstatement)
for x in bankstm:
konto_ut = (x["FIELD7"])
print(float(konto_ut))
for i in bankstm:
konto_inn = (i["FIELD8"])
print(float(konto_inn))
Json Data
{
"FIELD1": "2020-09-01",
"FIELD2": "2020-09-02",
"FIELD3": "50001685147",
"UTGÅENDE SALDO": "NO1300000000000",
"9759,52": "Visa",
"FIELD6": "*9808 31.08 Nok 22.00 Extra Bislett Kurs: 1.0000",
"FIELD7": "22,00",
"FIELD8": ""
},
Error:
ValueError: could not convert string to float: ''
For the one with a comma, it should be changed to a .
which is the standard for decimal points in Python:
konto_ut = x["FIELD7"].replace(",", ".")
print(float(konto_ut)) # 22.0
For empty strings, you can check if it's empty before printing as a float:
konto_inn = i["FIELD8"]
print(float(konto_inn) if (konto_inn != "") else 0) # 0
Another option would be to catch the exception which will avoid other potential issues with float conversions:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
konto_inn = i["FIELD8"]
if (is_number(konto_inn):
print(float(konto_inn))
else:
print("Not a number")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.