简体   繁体   中英

How to remove unwanted double quotes when converting CSV to GeoJSON

I'm getting started with Python3 and I'm working on a script to convert a CSV file into a GeoJSON one. The conversion works but I still have a problem with the coordinates, that are not taking the right format. I need to remove the double quotes, but it's not working.

Here is part of my code:

def readCsvFile():
    features=[]
    geoJson={}
    with open('resources/data_export.csv',newline= '') as csvfile:
        csvReader = csv.DictReader(csvfile,delimiter=',',quotechar='|')
        for row in csvReader:
            features.append({'type': 'Feature',
                            'geometry': {
                                'type': 'Point', "coordinates" : [str(row['longitude']), str(row['latitude'])]}, 'properties': {'id': decodeString(row['id']), 'field1': decodeString(row['field1']), 'field2': decodeString(row['field2'])})

    geoJson = {'type': 'FeatureCollection', 'features': features}
    return json.dumps(geoJson)

I'm getting that result:

{"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type": "Point", "coordinates": ["16.394564", "48.246426"]}, "properties": {"id": "0", ...

While I'm supposed to get:

{"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type": "Point", "coordinates": [16.394564, 48.246426]}, "properties": {"id": "0",

尝试将其转换为浮点数而不是字符串:

"coordinates" : [float(row['longitude']), float(row['latitude'])]}

I've done quite a few of these in different projects. I like using pandas and rewrote a code sample you could use (if you are interested that is). Pandas will make sure your columns convert automatically to float.

import pandas as pd
import json
import requests

def df2geojson(df, latlng = []):
    """Function converting pandas table to GEOJSON-format-string"""
    features = []
    for ind, row in df.iterrows():
        geometry = dict(type='Point', coordinates=row[latlng].tolist())
        properties = {k:v for k,v in row.items() if k not in latlng}
        features.append(dict(type='Feature',geometry=geometry, properties=properties))
    return dict(type="FeatureCollection",features=features)

data = '''\
id,field1,field2,longitude,latitude
0,100,100,0,16.394564,48.246426
1,200,200,0,16.494564,48.346426'''

filelikeobject = pd.compat.StringIO(data)          # simulates a file-object
df = pd.read_csv(filelikeobject)                   # should be: 'resources/data_export.csv'
jsonstr = df2geojson(df, ['latitude','longitude']) # pass dataframe and latlng colnames

#with open('output.geojson','w') as f:              # finally write to file
#    json.dump(jsonstr,f,indent=2)                  # disabled

baseurl = 'http://geojson.io/#data=data:application/json,'     # geojson.io url
url = baseurl+requests.utils.requote_uri(json.dumps(jsonstr))  # encode the json

print(url)

Results in an URL that you can click (use file dump if large file): http://geojson.io/#data=data:application/json,%7B%22type%22:%20%22FeatureCollection%22,%20%22features%22:%20[%7B%22type%22:%20%22Feature%22,%20%22geometry%22:%20%7B%22type%22:%20%22Point%22,%20%22coordinates%22:%20[48.246426,%2016.394564000000003]%7D,%20%22properties%22:%20%7B%22id%22:%20100.0,%20%22field1%22:%20100.0,%20%22field2%22:%200.0%7D%7D,%20%7B%22type%22:%20%22Feature%22,%20%22geometry%22:%20%7B%22type%22:%20%22Point%22,%20%22coordinates%22:%20[48.346426,%2016.494564]%7D,%20%22properties%22:%20%7B%22id%22:%20200.0,%20%22field1%22:%20200.0,%20%22field2%22:%200.0%7D%7D]%7D

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM