Python) How do I convert float type to string when I create json file?

Asked 2 years ago, Updated 2 years ago, 35 views

We are working on code to convert excel file to json file. In the meantime, the part that needs to go into the string is float type, so I'm having a hard time I don't know how to change float type to string.

Below is the code in progress.

import xlrd
from collections import OrderedDict
import json

excel_path = 'data.xlsx'
wb = xlrd.open_workbook(excel_path)
sh = wb.sheet_by_index(0)

data_list = []

for rownum in range(1, sh.nrows):
    data = OrderedDict()
    row_values = sh.row_values(rownum)

    data['col1'] = int(row_values[0])

    if type(row_values[1]) == float:
        data['col2'] = chr(row_values[1]) # This is it!
    else:
        data['col2'] = row_values[1]

    data['col3'] = row_values[2]
    data['col4'] = row_values[3]
    data['col5'] = int(row_values[4])
    data['col6'] = row_values[5]
    data['col7'] = row_values[6]
    data['col8'] = row_values[7]
    data['col9'] = row_values[8].split(', ')

    data_list.append(data)

j = json.dumps (data_list, sense_ascii=False) #Required for normal display in Korean

with open('data.json', 'w', -1, "utf-8") as f:
    f.write(j)

print(j)

python json

2022-09-20 19:26

2 Answers

str(1.2345)

But is there a reason why I have to convert it to string in the first place?

Can't you just do it right away? To json dump..

Note.

https://docs.python.org/3/library/stdtypes.html#str


2022-09-20 19:26

(Laughing) I've been googling around, but it's working because I'm doing del str ...I've never set the variable, hahaha...

...............


2022-09-20 19:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.