python - 更改字典中项目的数据类型
问题描述
我有一个.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 中解决这个问题,或者只是一个文件操作?我会很感激你的想法。
解决方案
我认为香草蟒对此很好,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)
推荐阅读
- mysql - 如何正确连接三个表
- python - Python 脚本在 Windows 的 Ubuntu 子系统中失败 - ModuleNotFoundError
- linux - 如何确定 Linux 版本是否支持写时复制 fork()
- php - PHP file_exists() 看到文件虽然它不存在
- javascript - 加载 pdf.js 以用于 chrome 扩展的内容脚本
- c++ - 具有用户定义指针成员的对象的赋值运算符
- laravel-5 - 主管运行队列:工作但不执行排队的 laravel 作业
- python - session.credentials() 如何在 AWS 中设置连接有用?
- java - WebView - 如果存在返回历史记录,则仅显示返回按钮
- python - 如何通过 MQTT 发布多个号码?