gpt4 book ai didi

python - 在 python 中将 CSV 转换为 JSON 时如何控制节点名称

转载 作者:太空宇宙 更新时间:2023-11-03 20:42:15 25 4
gpt4 key购买 nike

我在 python 中使用一个简单的 csv 到 json 脚本,并且我已经使用此成功将 CSV 转换为 JSON...

csvFilePath = ("x.csv")

# Read the CSV and add the data to a dictionary
data = {}
with open(csvFilePath) as csvFile:
csvReader = csv.DictReader(csvFile)
for csvRow in csvReader:
objectid = csvRow["objectid"]
data[objectid] = csvRow
d = csvrow

# Converts dictionary to JSON list
json_string = json.dumps([data], indent = 4)

生成的 JSON 如下所示...

[
{
"15494": {
"status": "Open",
"site_name": "Healthpromed Municipality of Vieques",
"objectid": "15494",
"utilities": "No",
"site_dashboard_surrogate_key": "BPS-H80-019569",
"supplies": "No",
"structural": "No",
"staff": "No"
},
"1": {
"status": "Closed",
"site_name": "PUBLIC HEALTH AND HUMAN SERVICES, MONTANA DEPARTMENT OF",
"objectid": "1",
"utilities": "No",
"site_dashboard_surrogate_key": "010478A2-14EF-4B7B-84A0-2618F311D82F",
"supplies": "No",
"structural": "No",
"staff": "No"
}
}]

我需要帮助更改由“objectid”设置为“attributes”的节点名称(即“15494”、“1”)

我想要的代码应该是这样的......

[
{
"attributes": {
"status": "Open",
"site_name": "Healthpromed Municipality of Vieques",
"objectid": "15494",
"utilities": "No",
"site_dashboard_surrogate_key": "BPS-H80-019569",
"supplies": "No",
"structural": "No",
"staff": "No"
},
"attributes": {
"status": "Closed",
"site_name": "PUBLIC HEALTH AND HUMAN SERVICES, MONTANA DEPARTMENT OF",
"objectid": "1",
"utilities": "No",
"site_dashboard_surrogate_key": "010478A2-14EF-4B7B-84A0-2618F311D82F",
"supplies": "No",
"structural": "No",
"staff": "No"
}
}]

有什么想法吗?我在这里无计可施。我尝试将 for 循环中的 objectid = csvRow["objectid"] 替换为 ["attributes"],但它只是覆盖了第一个条目。

最佳答案

未经测试,但我想根据 ArcGIS REST API 文档,这就是您所需要的。希望对您有帮助:)

csvFilePath = ("x.csv")

# Read the CSV and add the data to a dictionary
data = [] # make it a list
object = {} # initialize a dictionary
with open(csvFilePath) as csvFile:
csvReader = csv.DictReader(csvFile)
for csvRow in csvReader:
object['attributes'] = csvRow["objectid"] # create dictionary
data.append(dict(object)); # append every dictionary to list
d = csvrow

# Converts dictionary to JSON list
json_string = json.dumps(data, indent = 4) # make json dump your list of dictionary

关于python - 在 python 中将 CSV 转换为 JSON 时如何控制节点名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56794920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com