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

标签 python json csv geojson

下面的代码在执行时没有给我任何错误。但是,当我将文件拖/放到 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.

关于python - 将整个 csv 转换为 json 文件- python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30132999/

相关文章:

json - Swift json 时间值到本地时区

python - 如何使用 pandas 从 csv 中读取一行,进行 VLOOKUP 操作并将结果保存到另一个文件中?

json - 使用正确的引号从 Bigquery 导出表中的 JSON 值

python - 如何更改conda base的路径

python - 如何包装自定义 future 以在 Python 中与 asyncio 一起使用?

python - 无法使用自定义小部件更改可检查 QListViewItem 的状态

Java REST客户端——将curl代码重写为Java代码

angularjs - 抛出新的 ERR_INVALID_ARG_TYPE ('chunk' , ['string' ,'Buffer' ],chunk);TypeError[ERR_INVALID_ARG_TYPE] :The "chunk" arg must be type string or Buffer

python - 使用 Python 保存下载的 CSV 文件

python - 将列 append 到新数据框