将整个csv转换为json文件python

2024-03-29 12:39:12 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码在执行时不会给我任何错误。但是,当我将文件拖放到url中时:地理JSON.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'

Tags: 文件csvcsvfileimportjsontimeopenreader
1条回答
网友
1楼 · 发布于 2024-03-29 12:39:12

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

更重要的是,没有迹象表明您正在创建有效的geojson。您导入了库,但不使用它。您可能应该查看位于https://github.com/frewsxcv/python-geojsonGeoJSON 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.

相关问题 更多 >