我是 Python 新手,我想搜索并替换 JSON 文件中的 ID 标题。通常我会使用 R 来完成这个任务,但是如何在 Python 中完成它。这是我的 JSON 代码示例(带有服务 ID 和层 ID)。我有兴趣替换图层 ID 中的标题:
...{"services": [
{
"id": "service",
"url": "http://...",
"title": "GEW",
"layers": [
{
"id": "0",
"title": "wrongTitle",
},
{
"id": "1",
"title": "againTitleWrong",
},
],
"options": {}
},],}
对于替换,我将使用这样的表/csv:
serviceID layerID oldTitle newTitle
service 0 wrongTitle newTitle1
service 1 againTitleWrong newTitle2
....
你有什么想法吗?谢谢
最佳答案
这是一个working example在 repl.it 上。
代码:
import json
import io
import csv
### json input
input = """
{
"layers": [
{
"id": "0",
"title": "wrongTitle"
},
{
"id": "1",
"title": "againTitleWrong"
}
]
}
"""
### parse the json
parsed_json = json.loads(input)
#### csv input
csv_input = """serviceID,layerID,oldTitle,newTitle
service,0,wrongTitle,newTitle1
service,1,againTitleWrong,newTitle2
"""
### parse csv and generate a correction lookup
parsed_csv = csv.DictReader(io.StringIO(csv_input))
lookup = {}
for row in parsed_csv:
lookup[row["layerID"]] = row["newTitle"]
#correct and print json
layers = parsed_json["layers"]
for layer in layers:
layer["title"] = lookup[layer["id"]]
parsed_json["layers"] = layers
print(json.dumps(parsed_json))
关于Python:如何搜索和替换 json 文件的部分内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38791384/