python - python自定义json转换表JSONEncoder csv转json
问题描述
我正在尝试将 CSV 转换为 json 以便与 elasticsearch 一起使用。这是一个示例 csv:
user,user_creation_time
UserName1,2018-02-21T15:57:53+00:00
UserName2,N/A
数组类型:user
- str
,
user_creation_time
- ISO 时间或str('N/A')
问题是 ElasticSearch 摄取失败,N/A
因为它需要 type date
。
我有更多关于这个问题的时间字段(一旦是日期,一旦是字符串)。实现这一目标的最佳方法是什么?
最后的功能应该是:
CSV
user,user_creation_time
UserName1,2018-02-21T15:57:53+00:00
UserName2,N/A
Python
{"user":"UserName1","user_creation_time":"2018-02-21T15:57:53+00:00"}
{"user":"UserName2","user_creation_time":None}
json
{"user":"UserName1","user_creation_time":"2018-02-21T15:57:53+00:00"}
{"user":"UserName2","user_creation_time":null}
我现在要做的是:
import csv
with open(csv_file, 'r') as inf:
reader = csv.DictReader(inf.readlines())
print(json.dumps(tuple(reader)))
解决方案
我最终按照@stovfl 的建议做了同样的事情。并创建了这个https://gist.github.com/1oglop1/9950b033dc655f675ebc11ac122ab815
另一个肮脏的解决方案是替换字符串中的值,将其转换为 json,将 json 转储为字符串,替换不同的值并在再次加载时获得正确的结构
with open(csv_file, 'r') as inf:
file_content = inf.read()
no_na = file_content.replace('N/A', '').replace('not_supported', '')
rdr = csv.DictReader(no_na.splitlines())
records = json.dumps(tuple(rdr))
fixed_json = records.replace('""', "null").replace('"false"', "false").replace("'true'", "true")
print('jsn',records)
print(fixed_json)
print(json.loads(fixed_json)) # correct dict
推荐阅读
- django - Django迁移错误:应用程序不提供模型
- algorithm - 在说谎者问题中求解说谎者的上限和下限
- java - 如何编写单元测试用例来测试会话 cookie 的安全属性
- c# - 如何在cshtml中查看不同分类的文章?
- wordpress - 成功付款后Woocommerce订单失败问题
- r - 如何叠加多个图
- java - toArray() 函数如何确保 long 类型的列表不能转换为 Integer 的数组
- error-handling - 在给定选项和默认选项中都没有指定有效的“发件人”地址
- tensorflow - Tensorflow 超参数调整 - 未输出每个试验的指标
- c# - “转到实现”以“符号没有实现”结尾