在python中使用json将数字格式化为float或int

2024-09-28 21:14:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个CSV文件,里面有数据-

 Time,site_name,cell_name,RRC_attempts,rrc_succ_rate
 2018-01-12T08:37:00-06:00,910536_ARPIN,910536-24,1,100.0
 2018-01-12T08:37:00-06:00,910536_ARPIN,910536-34,0,0.0
 2018-01-12T08:37:00-06:00,910536_ARPIN,910536-14,5,100.0

我使用python中的json模块将csv转换为json

^{pr2}$

我现在的输出是-

        [
          {
            "Time": "2018-01-12T08:37:00-06:00",
            "site_name": "910536_ARPIN",
            "cell_name": "910536-24",
            "RRC_attempts": "1",
            "rrc_succ_rate": "100.0"
          },
          {
            "Time": "2018-01-12T08:37:00-06:00",
            "site_name": "910536_ARPIN",
            "cell_name": "910536-34",
            "RRC_attempts": "0",
            "rrc_succ_rate": "0.0"
          },
          {
            "Time": "2018-01-12T08:37:00-06:00",
            "site_name": "910536_ARPIN",
            "cell_name": "910536-14",
            "RRC_attempts": "5",
            "rrc_succ_rate": "100.0"
          }
        ]

我想要的输出是-

        [
          {
            "Time": "2018-01-12T08:37:00-06:00",
            "site_name": "910536_ARPIN",
            "cell_name": "910536-24",
            "RRC_attempts": 1,
            "rrc_succ_rate": 100
          },
          {
            "Time": "2018-01-12T08:37:00-06:00",
            "site_name": "910536_ARPIN",
            "cell_name": "910536-34",
            "RRC_attempts": 0,
            "rrc_succ_rate": 0
          },
          {
            "Time": "2018-01-12T08:37:00-06:00",
            "site_name": "910536_ARPIN",
            "cell_name": "910536-14",
            "RRC_attempts": 5,
            "rrc_succ_rate": 100
          }
        ]

如何告诉json将数字解析为int或float而不是字符串?请告知。 注意-在编写CSV文件时,我使用int()或float()将值显式转换为int或float。在


Tags: 文件csvnamejsonratetimesitecell
3条回答

这里有一种方法,您不必事先知道哪些值是数值:

import json
import csv

def numerify(row):
    for k, v in list(row.items()):
        try:
            row[k] = float(v)
            row[k] = int(v)
        except ValueError:
            pass

csvfile_ind = open("test.csv",'r')

reader_ind = csv.DictReader(csvfile_ind)
json_file_ind = open("test_json.json", 'w')
for row in reader_ind:
    numerify(row)
    json_file_ind.write(json.dumps(row,sort_keys=False, indent=4, separators=(',', ': ')))

在创建字典Parse int()和{}时,自己解析csv,输出到json:

import json 

with open("test.csv",'r') as f:
    # read lines, strip newlines, split at ,
    lines = [ x.strip('\n').split(',') for x in f.readlines()]    


listDic = []
for lineIndex in range(1,len(lines)):
    row = lines[lineIndex]     # get data row
    row[3] = int(row[3])       # convert data
    row[4] = float(row[4])     # convert data

    # zip to tuples of (key,value) and append to result list of dicts 
    listDic.append( dict( zip(lines[0],row)))  


with open("test_json.json", 'w') as json_file_ind:
    for row in listDic:
        json_file_ind.write(json.dumps(row,sort_keys=False, 
                            indent=4, separators=(',', ': ')))

Output:(由json_file_ind-调用创建的文件内容)

^{pr2}$

不要将每一行作为对json.dumps()的单独调用编写。将所有行收集到一个列表中,并一次性将其全部转储。在

要将字符串字段转换为整数,请对dict中的那些条目调用int()。在

import json
import csv

with csvfile_ind = open("test.csv",'r'):
    reader_ind = csv.DictReader(csvfile_ind)
    rows = []
    for row in reader_ind:
        row["RRC_attempts"] = int(row["RRC_attempts"])
        row["rrc_succ_rate"] = int(row["rrc_succ_rate"])
        rows.append(row)

with json_file_ind = open("test_json.json", 'w'):
    json.dump(rows, json_file_ind, sort_keys=False, indent=4, separators=(',', ': '))

相关问题 更多 >