简体   繁体   中英

How to substitute value for a variable in a json in python?

#!/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)

In the above script, I created a UUID and assigned it to the variable random_uuid . I want the UUID that was created to be substituted inside json for the value random_uuid for the key id . But, the above script is not substituting the value of random_uuid and just using the variable random_uuid itself.

Can anyone please tell me what I'm doing wrong here?

Thanks in advance.

You'll can use string formatting for that.

In your JSON string, replace random_uuid with %s, than do:

payload = payload % random_uuid

Another option is to use json.dumps to create the json:

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

payload = json.dumps(payload_dict)

Use str.format instead:

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

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

This code may help.

#!/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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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