【问题标题】:Convert JSON *files* to CSV *files* using Python (Idle)使用 Python 将 JSON *files* 转换为 CSV *files*(空闲)
【发布时间】:2012-12-01 09:46:06
【问题描述】:

这个问题搭载了我昨天发布的question。实际上,我的代码可以正常工作。我从小处着手。我为 Python 代码的多个 JSON 文件 outside 切换了 JSON in Python 代码。我实际上让它工作得很好。然后发生了某种灾难,我的代码丢失了。

我花了几个小时试图重新创建它,但无济于事。我实际上正在使用 arcpy(ArcGIS 的 Python 模块),因为稍后我将使用它来执行一些空间分析,但我认为您不需要了解太多关于 arcpy 的知识来帮助我完成这部分(我不认为,但它可能会有所帮助)。

这是我最近尝试的一个版本,但它不起作用。我将我的实际路径切换为“路径名”。实际上,当我尝试填充 CSV 中的行(具有纬度和经度值。它 成功写入纬度/经度时,我实际上已经完成了所有工作直到 CSV 文件中的标题)。所以显然dict_writer.writerows(openJSONfile) 下面的任何东西都不起作用:

import json, csv, arcpy
from arcpy import env

arcpy.env.workspace = r"C:\GIS\1GIS_DATA\Pathname"

workspaces = arcpy.ListWorkspaces("*", "Folder")
for workspace in workspaces:

    arcpy.env.workspace = workspace
    JSONfiles = arcpy.ListFiles("*.json")

    for JSONfile in JSONfiles:

        descJSONfile = arcpy.Describe(JSONfile)
        JSONfileName = descJSONfile.baseName

        openJSONfile = open(JSONfile, "wb+")
        print "JSON file is open"

        fieldnames = ['longitude', 'latitude']
        with open(JSONfileName+"test.csv", "wb+") as f:
            dict_writer = csv.DictWriter(f, fieldnames=fieldnames)
            dict_writer.writerow(dict(zip(fieldnames, fieldnames)))
            dict_writer.writerows(openJSONfile)

        #Do I have to open the CSV files? Aren't they already open?
        #openCSVfile = open(CSVfile, "r+")

    for row in openJSONfile:
         f.writerow( [row['longitude'], row['latitude']] )

非常感谢任何帮助!

【问题讨论】:

  • 什么实际上不起作用?也就是说,它会崩溃吗?您是否期望它执行 X 但实际上它执行 Y?它什么都不做?
  • 使用dict_writerwriteheader() 方法写入标题,然后使用其writerow() 写入行。每行都必须是映射其值的字段名字典。
  • @katrielalex 我上面解释的最后一行说明了什么不起作用:虽然代码成功填充了 CSV 文件中的标题,但它没有填充 JSON 文件中的实际值进入 CSV 的行(在标题下方)。所以我得到的 CSV 看起来像这样:纬度、经度(但下面没有值)。
  • @martineau 您介意为我重写并粘贴该代码块,以便我明白您的意思吗?我是新手,所以我不确定将您建议的代码放在哪里。

标签: python json csv arcgis arcpy


【解决方案1】:

您实际上并未加载 JSON 文件。
您正在尝试从打开的文件中写入行,而不是从 json 中写入行。

您需要添加如下内容:

rows = json.load(openJSONfile)

及以后:

dict_writer.writerows(rows)

您应该删除最后两行,因为所有 csv 写入都是在您到达它们之前完成的,并且它们在循环之外,所以无论如何它们只能用于最后一个文件(它们不写任何东西,因为此时文件中没有任何行)。

另外,我看到您使用 with open... 打开 csv 文件,而不是 json 文件。
您应该始终使用它,而不是使用没有with 语句的open()

【讨论】:

  • 我已经尝试过了 :( 当我在 fieldnames = ['longitude', 'latitude'] 行上方添加 rows = json.loads(openJSONfile) 时,我收到以下错误:TypeError: expected string or buffer
  • 哦,对不起,应该是json.load()
  • 我会写像with open(JSONfile, "wb+") as openJSONfile: 这样的东西吗?当我这样做时,我收到错误:"No JSON object could be decoded"(冒号后没有任何缩进...不知道该放什么)。
  • 只有json.load(openJSONfile) 我收到了"No JSON object could be decoded"error
【解决方案2】:

您应该使用csv.DictWriter 对象来执行所有操作。这是与您的代码类似的东西,因为我没有它,所以删除了所有 Arc 东西,这在我测试时有效:

import json, csv

JSONfiles = ['sample.json']

for JSONfile in JSONfiles:

    with open(JSONfile, "rb") as openJSONfile:
        rows = json.load(openJSONfile)

    fieldnames = ['longitude', 'latitude']
    with open(JSONfile+"test.csv", "wb") as f:
        dict_writer = csv.DictWriter(f, fieldnames=fieldnames)
        dict_writer.writeheader()
        dict_writer.writerows(rows)

没有必要写出每一行,因为您的 json 文件是行字典列表(假设它是您嵌入在链接问题中的内容)。

【讨论】:

  • 现在我收到此错误:IOError: [Errno 2] No such file or directory: u'Bus02_00_00_LP.json'(这是我的第一个 json 文件的名称)
  • 我尝试了print os.path.isfile(r"C:\GIS\1GIS_DATA\MyPath\FileName.json") 并得到了True,所以它就在那里......
  • 打开文件与我建议的处理无关,假设文件可以正常打开。
  • 非常感谢您的帮助。你知道为什么我在 with open(JSONfile, "rb") as openJSONfile:rows = json.load(openJSONfile) 行之后收到没有这样的文件或目录的错误吗?我到处找……什么都没有。
  • 您能否在问题发生时添加回溯的副本。这也应该准确显示发生错误时它所在的行。
【解决方案3】:

我不能说我确定出了什么问题,但是将所有 .JSON 文件与我的代码放在同一个文件夹中(并适当地更改我的代码)是可行的。我将不得不继续调查为什么在尝试读取其他文件夹时会出现错误:

IOError: [Errno 2] No such file or directory:

现在,下面的代码可以工作:)

import json, csv, arcpy, os
from arcpy import env

arcpy.env.workspace = r"C:\GIS\1GIS_DATA\MyFolder"

JSONfiles = arcpy.ListFiles("*.json")
print JSONfiles

for JSONfile in JSONfiles:
    print "Current JSON file is: " + JSONfile

    descJSONfile = arcpy.Describe(JSONfile)
    JSONfileName = descJSONfile.baseName

    with open(JSONfile, "rb") as openJSONfile:
        rows = json.load(openJSONfile)      
        print "JSON file is loaded"

    fieldnames = ['longitude', 'latitude']
    with open(JSONfileName+"test.csv", "wb") as f:
        dict_writer = csv.DictWriter(f, fieldnames = fieldnames)
        dict_writer.writerow(dict(zip(fieldnames, fieldnames)))
        dict_writer.writerows(rows)
        print "CSVs are Populated with headers and rows from JSON file.", '\n'

感谢大家的帮助。

【讨论】:

  • 我怀疑这与JSONfileName 的值有关。不过,不确定为什么文件夹的名称很重要。为什么你使用JSONfileName 而不仅仅是JSONfile
猜你喜欢
  • 2012-11-30
  • 1970-01-01
  • 2011-10-14
  • 2018-01-04
  • 2019-02-23
  • 2021-09-01
  • 2021-12-03
相关资源
最近更新 更多