Я хотел бы преобразовать группу файлов CSV в определенный формат файлов .JSON в Python.
Это мой пример файла CSV:
L1-CR109 Security Counter,has been forced,2019-02-26
L1-CR109 Security Counter,has been forced,2019-02-26
L1-CR109 Security Counter,has been forced,2019-02-26
L1-CR109 Security Counter,has been forced,2019-02-26
.. и этомой желаемый вывод json:
{ "index" : { "_index" : "test", "_type" : "_doc", "_id" : "1" } }
{ "location" : "L1-CR109 Security Counter", "door_activity": "has been forced", "2019-02-26"}
{ "index" : { "_index" : "test", "_type" : "_doc", "_id" : "1" } }
{ "location" : "L1-CR109 Security Counter", "door_activity": "has been forced", "2019-02-26"}
{ "index" : { "_index" : "test", "_type" : "_doc", "_id" : "1" } }
{ "location" : "L1-CR109 Security Counter", "door_activity": "has been forced", "2019-02-26"}
{ "index" : { "_index" : "test", "_type" : "_doc", "_id" : "1" } }
{ "location" : "L1-CR109 Security Counter", "door_activity": "has been forced", "2019-02-26"}
В настоящее время мне удалось получить следующий результат в формате json:
[{"location": "L1-CR109 Security Counter", "door_status": "has been forced", "date": "2019-02-21"},
{"location": "L1-CR109 Security Counter", "door_status": "has been forced", "date": "2019-02-21"},
{"location": "L1-CR109 Security Counter", "door_status": "has been forced", "date": "2019-02-21"},
{"location": "L1-CR109 Security Counter", "door_status": "has been forced", "date": "2019-02-21"}
.. и это мой код Python:
def csv_to_json():
in_file = '/Elastic Search/Converted Detection/Converted CSV'
out_file = '/Elastic Search/Converted Detection/Converted JSON'
for filename in os.listdir(in_file):
print("\n")
print("Converting " + filename + " file...")
with open(in_file + "/" + filename, 'r') as f:
if filename.endswith(".csv"):
reader = csv.DictReader(f, fieldnames=("location", "door_status", "date"))
out = json.dumps([row for row in reader])
text_file = open(out_file + r'/{}.json'.format(filename[:-4]), 'w')
text_file.write(out + "\n")
Я пытался найти решение, но безрезультатно.Могу ли я узнать, что мне не хватает в коде?Опять же, могу ли я получить совет о том, почему Elastic Search допускает только мой желаемый выходной формат json с индексом вместо обычного формата python?