在 python3 中的 <Class str> 数组中添加字符串?

Adding string in <Class str> array in python3?

我有下面这样的字符串

data = '[{"cId": "y02", "name": "Test 02", "description": "My Test"}]'

我正在像

这样的 http 请求中发送此数据
import requests

headers = {
    'Content-Type': 'application/json',
}  
response = requests.post('http://localhost:8000/targets', headers=headers,data=data, auth=('user', 'pass'))

现在我想做的是,例如我在变量中有一个字符串,例如..

id=str('random string')

我想将它添加到这样的数据中..

data = '[{"cId": id, "name": "Test 02", "description": "My Test"}]'

但是我无法添加它。我试图先转换 json 中的条目,然后将其添加到数组中。但是服务器发回异常。我该怎么做?

您可以将其转换为列表 dicts.Then 将其转换为 str。(使用 json 模块):

import json

data_before = '[{"cId": "y02", "name": "Test 02", "description": "My Test"}]'
tmp = json.loads(data_before)
tmp[0]["cId"] = str('random string')
data_after = json.dumps(tmp)

然后像以前一样使用data_after:

import requests

headers = {
    'Content-Type': 'application/json',
}
response = requests.post('http://localhost:8000/targets', headers=headers, data=data_after, auth=('user', 'pass'))

或者直接在requests.post中作为json参数传递:

import json

data_before = '[{"cId": "y02", "name": "Test 02", "description": "My Test"}]'
data_after = json.loads(data_before)
data_after[0]["cId"] = str('random string')

然后做:

import requests

headers = {
    'Content-Type': 'application/json',
}  
response = requests.post('http://localhost:8000/targets', headers=headers, json=data_after, auth=('user', 'pass'))

request.post() 中的数据应该是:

Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:Request.

如果您的数据是 json 格式,您可以加载数据并使用 json.load("<str in json format>").

将字符串转换为字典