Skip to main content
 首页 » 编程设计

python之将整个 csv 转换为 json 文件- python

2025年05月04日10unruledboy

下面的代码在执行时没有给我任何错误。但是,当我将文件拖/放到 url: geojson.io 时,我得到以下“无效的 Json 文件:语法错误意外标记”。

#!/usr/bin/python 
 
import csv 
import json 
import geojson 
 
csvfile = open('May_6th.csv', 'rU') 
jsonfile = open('file.json', 'w') 
 
fieldnames = {'type': 'FeatureCollection', 
        'features':[("Name","Bearing (True)","Bearing (Mag)", 
"Distance","Total Distance","Planned Speed",  
"Leg Time", "Total Time", "Turn", "Latitude", "Longitude")]} 
 
reader = csv.DictReader( csvfile, fieldnames) 
 
 
 
for row in reader: 
    json.dump(row, jsonfile) 
    jsonfile.write('\n') 
print 'csv file converted' 

请您参考如下方法:

按照大多数惯例,一个 JSON 文件代表一个 javascript 对象。您的文件是一系列对象,由换行符分隔。您创建的内容有时称为 JSRec .

更重要的是,没有迹象表明您正在制作有效的 geojson。您导入库但不使用它。您可能应该在 https://github.com/frewsxcv/python-geojson 查看文档或 GeoJSON format specification以确保您创建的文件符合 GeoJSON 格式。

我注意到 GeoJSON 规范明确指出:

GeoJSON always consists of a single object. This object (referred to as the GeoJSON object below) represents a geometry, feature, or collection of features.