Python:更改某些JSON数据并写入输出文件

时间:2015-09-30 15:40:35

标签: json python-2.7

我正在尝试将.json文件解析为.kml文件以供绘图程序使用。我将给出一组数据样本以简化问题:

我有一个LocationHistory.json文件,它具有以下结构:

,

我定义了一个解析json数据的函数,然后我想将它提供给“placemark”字符串以写入(输出)到“location.kml”文件中:

{
 "data" : {
   "items" : [ {
     "kind" : "latitude#location",
     "timestampMs" : "1374870896803",
     "latitude" : 34.9482949,
     "longitude" : -85.3245474,
     "accuracy" : 2149
   }, {
     "kind" : "latitude#location",
     "timestampMs" : "1374870711762",
     "latitude" : 34.9857898,
     "longitude" : -85.3526902,
     "accuracy" : 2016"
   }]
  }
}

此代码的目的是将包含.json数据的地标字符串写入location.ml文件,该地标字符串如下所示:

import json
import datetime

def parse_jason_data_to_kml_file():
   kml_file = open('location.kml', "r+")

   #Here I parse the info inside the LocationHistory.json file
   json_file = open('LocationHistory.json')
   json_string = json_file.read()
   json_data = json.loads(json_string)

   locations = json_data["data"]["items"]

   # Next, I create a placemark string template:
   placemark = ["<Placemark>",
                "<TimeStamp><when>%(timestampMs)r</when></TimeStamp>",
                "<ExtendedData>",
                "<Data name=\"accuracy\">",
                "<value>%(accuracy)r</value>]",
                "</Data>",
                "</ExtendedData><Point><coordinates>%(longitude)r, %(latitude)r</coordinates></Point>",
                "</Placemark>"]
   placemark = "\n".join(placemark)

   # Now I loop through the json data and write the json data into the
   # placemark templete and write each placemark to a KML file.
   for location in locations:
       temp = placemark % location
       kml_file.write("\n" + temp + "\n")

   kml_file.close()
   json_file.close()

   parse_jason_data_to_kml_file()

输出,如下所示:

<Placemark>
<TimeStamp><when>the “timestampMS” value from the JSON data item</when></TimeStamp>
<ExtendedData>
<Data name=”accuracy”>
<value> the “accuracy” value from the JSON data item </value>
</Data>
</ExtendedData><Point><coordinates>”longitude,latitude”</coordinates></Point>
</Placemark>

一切都运行良好,但我的问题在于我需要更改所有“timestampMs”信息(如LocationHistory.json文件中所示)。 1374870896803来自eg。 2013-07-26T10:24:24Z。 使用此代码,我可以将timestampMs打印为datetime对象:

<Placemark>
<TimeStamp><when>u'1374870896803'</when></TimeStamp>
<ExtendedData>
<Data name=”accuracy”>
<value>2149</value>
</Data>
</ExtendedData><Point><coordinates>-85.3245474,34.9482949</coordinates></Point>
</Placemark>

<Placemark>
<TimeStamp><when>u'1374870711762'</when></TimeStamp>
<ExtendedData>
<Data name=”accuracy”>
<value>2016</value>
</Data>
</ExtendedData><Point><coordinates>-85.3526902,34.9857898</coordinates></Point>
</Placemark>

换句话说:我想将每个时间戳更改为:(注意顶部的日期时间作为时间戳)

for location in locations:
   print datetime.datetime.fromtimestamp(int(location.get("timestampMs"))/1000).strftime("%Y-%m-%dT%H:%M:%SZ")

谢谢

1 个答案:

答案 0 :(得分:0)

在for循环的开头添加一个步骤:

TThread.Queue()