首页 > 解决方案 > 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)))

标签: pythonjsonelasticsearch

解决方案


我最终按照@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

推荐阅读