Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python-将geojson写入文件_Python_Geojson - Fatal编程技术网

python-将geojson写入文件

python-将geojson写入文件,python,geojson,Python,Geojson,我在玩Google Maps API,我想得到多段线,然后将其转换为Lat,Lon,然后转换为GeoJSON,这样我就可以用Mapbox将其可视化。我已经掌握了大部分的方法,但仍在研究如何将最终的GeoJSON写入文件 以下是我目前掌握的代码: #creates empty list for geoJSON geoList = [] for i in URLlist: polylineData = json.load(urllib2.urlopen(i)) # try ... ex

我在玩Google Maps API,我想得到多段线,然后将其转换为Lat,Lon,然后转换为GeoJSON,这样我就可以用Mapbox将其可视化。我已经掌握了大部分的方法,但仍在研究如何将最终的GeoJSON写入文件

以下是我目前掌握的代码:

#creates empty list for geoJSON
geoList = []

for i in URLlist:
    polylineData = json.load(urllib2.urlopen(i))


# try ... except will do what you want when true and put exceptions into false
    try:
        # looks up polyline string from JSON
        polylineExcerpt = polylineData['routes'][0]['overview_polyline']['points']
        # use polyline module to decode into lat,lon
        waypointData = polyline.decode(polylineExcerpt)

        # use geojson library to encode to GeoJSON
        encodeWaypoint = LineString(waypointData)

        # uses swapCoord function to reverse lat lon
        for feature in encodeWaypoint['coordinates']:
           flip = swapCoords(feature)
           appendLine = geoList.append(flip)

        # # puts it back into GeoJSON
         convertToGeoJSON = LineString(geoList)

     except: 
        print('something went wrong')
因此,我在一个列表中有所有JSON元素,但不确定如何使用正确的编码将其写入文件。如果我这样做:

with open('data.json', 'a') as f:
    json.dump(convertToGeoJSON, f)

那么它不会生成有效的JSON,有没有更好的方法来创建最终的JSON

您可以通过在循环的每次迭代中将一个GeoJSON添加到列表中来创建GeoJSON列表。最后,立即将Json数组写入文件

例如:

将其加载到python时,您可以简单地执行此操作

json=open('data.json') 
data = json.load(json)

你能打印
convertToGeoJSON
你说的“没有生成有效的json”是什么意思吗?@ZdaR是的,它一个接一个地打印每个geojson对象,但我不知道如何将它们组合成一个文件,用逗号分隔每个对象,用[start and]年底file@MarlonAbeykoon它将所有内容转储到一个文件中,但在每个对象之间或在文件的开头和结尾处没有逗号[and]。
json=open('data.json') 
data = json.load(json)