简体   繁体   English

Python - 在 JSON 文件中搜索和替换

[英]Python - Search and Replace in JSON file

I'd like to replace the displayName field in python:我想替换 python 中的 displayName 字段:

json = {
    "expand": "renderedFields,names,schema",
    "id": "743145",
    "self": "XXXXXXXXXXXX/api/2/issue/743145",
    "key": "TEST1234-1266",
    "fields": {
        "issuelinks": [],
        "assignee": {
            "self": "XXXXXXXXXXXX/api/2/user?username=XX.XX",
            "name": "ted.bundy@gmail.com",
            "key": "JIRAUSER22031",
            "avatarUrls": {
                "48x48": "XXXXXXXXXXXXjira/secure/useravatar?avatarId=10122",
                "24x24": "XXXXXXXXXXXXjira/secure/useravatar?size=small&avatarId=10122",
                "16x16": "XXXXXXXXXXXXjira/secure/useravatar?size=xsmall&avatarId=10122",
                "32x32": "XXXXXXXXXXXXjira/secure/useravatar?size=medium&avatarId=10122"
            },
            "displayName": "ted.bundy@gmail.com",
            "active": true,
            "timeZone": "Europe/London"
        },
        "components": [{
            "self": "XXXXXXXXXXXX/api/2/component/23015",
            "id": "23015",
            "name": "AWS_EC2",
            "description": "AWS_EC2"
        }]
    }
}

The way it is done currently is by a search and replace from a csv file.目前完成的方式是通过搜索和替换 csv 文件。

code:代码:

import json
import csv
import os
import requests

site = "https://xxxx.com/xxxxxx/rest/api/2/search?xxxx=project=UKTEST"

url = requests.get(site, auth=auth, )
url_json = mtd_list.json()
url_str = json.dumps(mtd_json)

with open("names.csv","r+") as data:

    # csv file
    csvInput = csv.reader(data)

    # Search and replace
    for row in csvInput:
        replacerow = url_str.replace(row[0], (row[1]),)
        url_str= replacerow

csv file contains: csv 文件包含:

ted.bundy@gmail.com tbundy

How would I get the above to work but with the url_json?如果不使用 url_json,我将如何使上述工作正常进行?

You can update json like this:您可以像这样更新 json:

url_json["displayName"] = ""

Whats the rule for changing displayName?更改显示名称的规则是什么? Its not clear in your question.你的问题不清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM