首页 > 解决方案 > 更改字典中项目的数据类型

问题描述

我有一个.txt包含 20,000 行此类字典的文件:

{ "seller_cd":"20559","order_cd":"121213123123","items":[{"item_cd":"45114","item_name":"ABC","width":"16.9","height":"3.4","depth":"13.8", "qty":"3"},{"item_cd":"4232","item_name":"xyz","width":"16.9","height":"1.5", "depth":"11.8","qty":"3"},{"item_cd":"45114","item_name":"xz","width":"16.6","height":"3.9","depth":"13.7","qty":"6"}]}

我正在尝试将数据类型更改为"width", "height", "depth"int/float

我试图将其转换为数据框,然后转换数据类型,但我想可能有更简单的方法来做到这一点。有没有一种有效的方法可以在 pandas 中解决这个问题,或者只是一个文件操作?我会很感激你的想法。

标签: pythonjsondictionary

解决方案


我认为香草蟒对此很好,20k 行根本不算多。

import json
from pathlib import Path
from ast import literal_eval


file = 'path_to_file'
with open(file,'r') as f:
    json_object = json.load(f) 


for item in json_object['items']:
    item['width'] =  literal_eval(item['width'])
    item['height'] = literal_eval(item['height'])
    item['depth'] =  literal_eval(item['depth'])

with open(Path(file).parent.joinpath('outfile.json'),'w') as f:
    json.dump(json_object ,f)

在此处输入图像描述


推荐阅读