如何在python中的json中替换变量的值?

时间:2016-04-13 06:41:04

标签: python json

#!/usr/bin/python
import requests
import uuid

random_uuid = uuid.uuid4()
print random_uuid
url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials"

payload = '''json={
        "": "0",
        "credentials": {
            "scope": "GLOBAL",
            "id": "random_uuid",
            "username": "testuser3",
            "password": "bar",
            "description": "biz",
            "$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
        }
    }'''
headers = {
    'content-type': "application/x-www-form-urlencoded",
    }

response = requests.request("POST", url, data=payload, headers=headers)

print(response.text)

在上面的脚本中,我创建了一个UUID并将其分配给变量random_uuid。我希望创建的UUID在json中替换为键random_uuid的值id。但是,上面的脚本不是替换random_uuid的值而只是使用变量random_uuid本身。

有谁能告诉我我在这里做错了什么?

提前致谢。

4 个答案:

答案 0 :(得分:1)

您可以使用字符串格式。

在您的JSON字符串中,将random_uuid替换为%s,而不是:

payload = payload % random_uuid

另一种选择是使用json.dumps来创建json:

payload_dict = {
    'id': random_uuid,
    ...
}

payload = json.dumps(payload_dict)

答案 1 :(得分:1)

改为使用str.format

payload = '''json={
        "": "0",
        "credentials": {
            "scope": "GLOBAL",
            "id": "{0}",
            "username": "testuser3",
            "password": "bar",
            "description": "biz",
            "$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
        }
    }'''.format(random_uuid)

答案 2 :(得分:1)

您可以将JSON直接输入到dict中: payload = { "": "0", "credentials": { "scope": "GLOBAL", "id": random_uuid, "username": "testuser3", "password": "bar", "description": "biz", "$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl" } }

答案 3 :(得分:0)

此代码可能有所帮助。

#!/usr/bin/python
import requests
import uuid

random_uuid = uuid.uuid4()
print random_uuid
url = "http://192.168.54.214:8080/credential-store/domain/_/createCredentials"

payload = '''json={
        "": "0",
        "credentials": {
            "scope": "GLOBAL",
            "id": "%s",
            "username": "testuser3",
            "password": "bar",
            "description": "biz",
            "$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"
        }
    }''' % random_uuid
headers = {
    'content-type': "application/x-www-form-urlencoded",
    }

print payload

print(response.text)