Python:如何搜索和替换 json 文件的部分内容?

标签 python json

我是 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/

相关文章:

iphone - 我可以使用 Python 编写原生 iPhone 应用程序吗?

java - 努力将 JSON 负载映射到模型类

javascript - 如何从angularjs中的json获取特定的唯一值

python - 无效参数错误 : cannot compute MatMul as input #0(zero-based) was expected to be a float tensor but is a double tensor [Op:MatMul]

python - 将用户输入从 tkinter 保存到变量并检查其内容

python - 寻找常闭日志文件的 Python 方法

json - 在显示 View 之前未读取 View 模型数据

android - 使用动态 JSON 对象名称解析 JSON?

javascript - 如何在nodejs中比较两个字符串源和目标与全名

python - 导入错误 : No module named 'tensorflow.python' with tensorflow-gpu