【问题标题】:Convert CSV file to array of json objects with Python使用 Python 将 CSV 文件转换为 json 对象数组
【发布时间】:2021-09-13 19:20:39
【问题描述】:

我有一个 CSV 文件,其中每一行代表一个 json 对象。我正在尝试将其转换为包含 json 对象数组的文件。

我应该事先声明,我不是一个经验丰富的 Python 开发人员。

CSV 文件中包含 2 个条目的示例数据:

{"first_name": "Jason", "last_name": "Elwood", "last_modified": {"type": "/type/datetime", "value": "2008-08-20T17:57:46.368856"}, "occupation": "developer"}

{"first_name": "Joe", "last_name": "Plumb", "last_modified": {"type": "/type/datetime", "value": "2008-08-20T17:57:46.368856"}, "occupation": "plumber"}

期望的输出:

[{
        "first_name": "Jason",
        "last_name": "Elwood",
        "last_modified": {
            "type": "/type/datetime",
            "value": "2008-08-20T17:57:46.368856"
        },
        "occupation": "developer"
    },
    {
        "first_name": "Joe",
        "last_name": "Plumb",
        "last_modified": {
            "type": "/type/datetime",
            "value": "2008-08-20T17:57:46.368856"
        },
        "occupation": "plumber"
    }
]

这是一些近似于我正在尝试做的 Python 代码(为了演示,我首先打印一个本地 json 格式的字符串,然后从读取的 CSV 文件中打印:

蟒蛇:

# Python3
# read CSV file to array of json objects
  
# initializing string 
test_string = '{"first_name": "Jason", "last_name": "Elwood", "last_modified": {"type": "/type/datetime", "value": "2008-08-20T17:57:46.368856"}, "occupation": "developer"}' 

print("test_string:")
print(test_string)

arr = []
arr.append(str(test_string))
# printing original string 
print("Array from test_string :")
print(arr)

arr = []
with open('testData.csv') as f:
    for row in f:
        arr.append(row)
    print("Array from file:")
    print(arr)

这是输出:

test_string:
{"first_name": "Jason", "last_name": "Elwood", "last_modified": {"type": "/type/datetime", "value": "2008-08-20T17:57:46.368856"}, "occupation": "developer"}
Array from test_string :
['{"first_name": "Jason", "last_name": "Elwood", "last_modified": {"type": "/type/datetime", "value": "2008-08-20T17:57:46.368856"}, "occupation": "developer"}']
Array from file:
['"{""first_name"": ""Jason"", ""last_name"": ""Elwood"", ""last_modified"": {""type"": ""/type/datetime"", ""value"": ""2008-08-20T17:57:46.368856""}, ""occupation"": ""developer""}"']

一个。硬编码的字符串打印得很好:即有效的 json 格式字符串。

b.一旦添加到数组中,硬编码的字符串就会被单引号括起来。

c。然而,csv 导入的字符串被引号包围,并且所有预先存在的引号都被复制。

重申一下,我想要一个可以轻松导入 NoSQL 数据库的 json 对象数组。

非常感谢任何帮助。如果我能提供更多信息来帮助描述我目前的情况和期望的结果,请告诉我。

提前致谢,祝您有美好的一天!

【问题讨论】:

  • 为什么不在这里使用 JSON 模块?
  • 谢谢,@tdelaney。已添加。
  • for row in f: arr.append(row) 这只是将f每一行 附加到arr。要将其转换为对象,您需要先将行解析为对象!查找json.loads()

标签: python json csv


【解决方案1】:

考虑到,“Test.csv”是包含 2 个条目的 CSV 文件名。请 找到将数据转储到 JSON 文件(“Test.json”)的代码。

import csv
import json


def main():
    # Read Test csv having 2 records
    with open("Test.csv") as csvfile:
        data = csv.reader(csvfile)
        result = [json.loads(record[0]) for record in data]

    # dump csv data to Test.json file
    with open("Test.json", "w") as jsonfile:
        json.dump(result, jsonfile)
    
    # read Test json file to validate data is dumped correctly or not
    with open("Test.json", "r") as jsonfile:
        data = json.loads(jsonfile.read())
        for record in data:
            print(record)
            
main()

【讨论】:

  • 谢谢你,Vimlesh!这似乎已经做到了。我很感激你在这方面的时间。你节省了我很多时间用头撞我的桌子。 :)
  • 所以这种方法适用于我的用例,但现在我有一个关于 JSONDecodeError 异常的问题。有没有办法跳过格式不正确的记录?例如,我希望能够在引发此异常时捕获它并跳过错误行并继续复制文件,忽略任何格式错误的行。谢谢!
  • result = [json.loads(record[0]) for record in data],这行我用列表理解写的。你可以把它写成正常的for循环和for循环内部,写try和expect块。如果是异常,就继续for循环。
【解决方案2】:

这不是 CSV 文件。它是一堆行分隔的 json 记录。您不想尝试将其作为 CSV 进行处理,因为所有这些逗号都将被视为列分隔符。

import json
with open("testfile.jsons") as fileobj:
    result = [json.loads(record) for record in fileobj]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-03
    • 2023-03-28
    • 1970-01-01
    • 2022-09-23
    • 2018-10-11
    • 2019-03-25
    • 2022-08-19
    • 2020-10-06
    相关资源
    最近更新 更多