GIS小技术分享(一):python中json数据转geojson或者shp

1.环境需求

  • geopands
  • pandas
  • shapely
  • json
  • python3

2.输入数据(path字段,线条)

[
	{
		"id": "586A685D568311B2A16F33FCD5055F7B",
		"name": "普及江",
		"path": "[[116.35178835446628,23.578775300642008],
		...
		[116.35907935999273,23.568280404942346],[116.35910326492889,23.568280404942346],[116.35912716986502,23.568280404942346]]",
		"level": "4"
	},
	{
		"id": "5836685D568311B28A99F515E230FBDA",
		"name": "合江",
		"path": "[[116.35164957162047,23.579086231394125],
...
[116.38827220661572,23.565004934530894]]
	},
	{
		"id": "5863685D568311B2B93B96948D95EE27",
		"name": "红河",
		"path": "[[116.3668636727083,23.548868772118134],[116.3668636727083,23.548858522164803],[116.3668636727083,23.54884827221066],
		...
		[116.3668636727083,23.54876627254877],[116.3668636727083,23.548735522662366]]
	},

3.转换代码
将数据转给geojson。转shp可以调整to_file方法的驱动参数。

import json
from shapely.geometry import LineString
import geopandas as gpd
import pandas as pd

def main(f):
  geoList = []
  tb = []
  with open(f,mode='r', encoding='utf-8') as ff:
    data = json.load(ff)
    df = pd.DataFrame(data)
    for i in range(0, len(data)):
      row = data[i]
      prop = df.iloc[i, :11]
      tb.append(prop)
      if (row['path']):
        line = LineString(row['path'])
        geoList.append(line)
      else:
        geoList.append(None)
    geoDataFrame = gpd.GeoDataFrame(tb, geometry=geoList)
    fp = 'res1.geojson'
    geoDataFrame.to_file(fp, driver='GeoJSON', encoding='utf-8')

f = r'z_river_1.txt'
main(f)

4.输出
转为geojson,在QGIS中验证。
GIS小技术分享(一):python中json数据转geojson或者shp_第1张图片

你可能感兴趣的:(python,json,pandas,json转shp)