【问题标题】:Adding string in <Class str> array in python3?在python3的<Class str>数组中添加字符串?
【发布时间】:2020-12-04 12:55:36
【问题描述】:

我下面有个这样的字符串

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 中的条目转换,然后将其添加到数组中。但是服务器将异常发回。我该怎么做?

【问题讨论】:

  • 您注意到data 是一个包含1 个元素的字典列表吗?
  • 我做了 type(data) 并且它显示了我 .
  • " 我尝试先转换 json 中的条目,然后将其添加到数组中。但是服务器将异常发送回来。我该怎么做?"你到底尝试了什么?

标签: python arrays python-3.x python-requests httprequest


【解决方案1】:

您可以将其转换为字典列表。然后将其转换为 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'))

【讨论】:

    【解决方案2】:

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

    要在 :class:Request 的正文中发送的字典、元组列表、字节或类似文件的对象。

    如果您的数据是 json 格式,您可以加载数据并将字符串转换为使用 json.load("&lt;str in json format&gt;") 的字典。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 2021-08-02
      • 2017-06-25
      相关资源
      最近更新 更多