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

时间:2016-08-05 14:12:51

标签: python json

我是Python的新手,我想在JSON文件中搜索和替换ID的标题。通常我会使用R来完成这个任务,但是如何在Python中使用它。这是我的JSON代码示例(带有服务ID和图层ID)。我有兴趣替换图层ID中的标题:

$httpProvider.interceptors.push(function($q, $cookies) {
    return {
     'request': function(config) {

          config.headers['Token'] = $cookies.loginTokenCookie;
          return config;
      }
    };
  });

对于替换我会使用像这样的表/ csv:

 ...{"services": [
                  {
                     "id": "service",
                     "url": "http://...",
                     "title": "GEW",
                     "layers": [
                        {
                           "id": "0",
                           "title": "wrongTitle",
                        },
                        {
                           "id": "1",
                           "title": "againTitleWrong",
                        },
                     ],
                     "options": {}
                  },],}

你有想法吗?感谢

3 个答案:

答案 0 :(得分:1)

这里是repl.it上的working example

代码:

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))   

答案 1 :(得分:0)

您不会说您正在使用的是哪个版本的Python,但是该语言有内置的JSON解析器。

对于2.x:https://docs.python.org/2.7/library/json.html

对于3.x:https://docs.python.org/3.4/library/json.html

这些应该能够帮助您解析JSON并替换您想要的内容。

答案 2 :(得分:0)

正如其他用户建议的那样,检查JSON模块会有所帮助。 这里给出了python2.7的基本示例:

    import json
    j = '''{
        "services":
                [{
                 "id": "service",
                 "url": "http://...",
                 "title": "GEW",
                 "options": {},
                 "layers": [
                    {
                       "id": "0",
                       "title": "wrongTitle"
                    },
                    {
                       "id": "1",
                       "title": "againTitleWrong"
                    }
                 ]             
                }]
    }'''
    s = json.loads(j)
    s["services"][0]["layers"][0]["title"] = "new title"
    # save json object to file
    with open('file.json', 'w') as f:
        json.dump(s, f)

您可以根据csv文件索引元素并更改其标题,这需要使用CSV模块。