【发布时间】: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()