import xml.etree.ElementTree as ET
import json


def make_placemark(name, desc, date_time, lat, lon):
    placemen_el = ET.Element("Placemark")
    time_stamp_el = ET.SubElement(placemen_el, "gx:TimeStamp")
    when_el = ET.SubElement(time_stamp_el, "when")
    tstmp = date_time.split('.')
    when_el.text = tstmp[2] + '-' + tstmp[1] + '-' + tstmp[0]
    name_el = ET.SubElement(placemen_el, "name")
    name_el.text = name
    description_el = ET.SubElement(placemen_el, "description")
    description_el.text = desc
    point_el = ET.SubElement(placemen_el, "Point")
    coordinates_el = ET.SubElement(point_el, "coordinates")
    coordinates_el.text = str(lon) + ',' + str(lat) + ',0'
    return placemen_el


def json2html(jj):
    tbl = r'<table border="1">'
    #
    if isinstance(jj, dict):
        for key, value in jj.items():
            if isinstance(value, dict) or isinstance(value, list):
                tbl += '<tr><th>' + str(key) + '</th><td>' + json2html(value) + '</td></tr>'
            else:
                tbl += '<tr><th>' + str(key) + '</th><td>' + str(value) + '</td></tr>'
    elif isinstance(jj, list):
        for ell in jj:
            if ell != "":
                tbl += '<tr><th>' + json2html(ell) + '</td></tr>'
    #
    tbl += '</table>'
    return tbl


el = ET.Element('kml', {'xmlns': 'http://www.opengis.net/kml/2.2', 'xmlns:gx': 'http://www.google.com/kml/ext/2.2'})
doc = ET.SubElement(el, "Document")
#
file_directory = r'C:\work1\crash_region_code_1165.json'
json_data=open(file_directory, 'r', encoding="utf-8").read()
str1 = json_data.split('\n')
for n in str1:
    if n != '':
        data = json.loads(n)
        geo_code = data['geo_code']
        doc.append(make_placemark(data['_id']['$oid'], json2html(data), data['em_moment_date'], geo_code['latitude'], geo_code['longitude']))

et = ET.ElementTree(el)
et.write(r'C:\work1\test44.kml', encoding='UTF-8', xml_declaration=True, method='xml')
