我正在尝试将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上失败了,因为它期望输入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)))发布于 2018-10-09 09:56:56
最后,我按照@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 dicthttps://stackoverflow.com/questions/52666528
复制相似问题