0

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: ''
deadshot
  • 8,881
  • 4
  • 20
  • 39
  • 1
    this will help [Checking if a string can be converted to float in Python](https://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python) – deadshot Sep 06 '20 at 11:01
  • 1
    Does this answer your question? [Checking if a string can be converted to float in Python](https://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python) – Tomerikoo Sep 06 '20 at 11:34
  • 1
    @deadshot why didn't you put this as a duplicate? sounds like one to me... – Tomerikoo Sep 06 '20 at 11:36
  • Make your program resistant to bad input. Exceptions use try+catch, find examples on internet and learn to use them everywhere where your class communicates with others. – Bart Mensfort Sep 06 '20 at 12:09

1 Answers1

0

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")
DenverCoder1
  • 2,253
  • 1
  • 10
  • 23