python - 我想在 json body 元素中发布一个对象列表
问题描述
我想使用一个包含键值列表的元素发出一个发布请求,其中包含多个对象。但是,当我将 JSON 数据放入我的请求正文中时,该元素会将 ' ' 放在整个列表周围,使其对于将接收数据的 Web 服务器不可序列化。
// the format should be like this ->{
"data1": str,
"data2": int,
"devices": {
"device1": [
{
"timestamp": int,
"temperature": int
},
... // More signals from same device
],
... // More devices for example device 2 same format etc.
}
}
但是,当我以相同的格式运行我的代码时,我最终得到了这个输出
{'data1': '1234', 'data2': 1234, 'devices': {'"device1": [{"temperature": 20, "timestamp": 1585776505}]}, {"device2": [{"temperature": 18, "timestamp": 1585776505}]'}} ///etc..
正如您在设备元素内部看到的,它的开头和结尾都是一个“'”,它破坏了格式,因此 Web 服务器无法接收数据。我不知道如何摆脱它。当我不将数据放入请求正文中时,格式看起来不错,“'”不存在。我首先通过制作一个字典来使用 python,该字典包含我收到的所有设备的列表,然后在使用后将它们放入请求正文中json.dumps()
。
mac_dict2 = {devicename:
[{"temperature" : temp,
"timestamp": int(time.time())}]
} // the format i want my list of devices to have
mac_list.append(mac_dict2) // mac_list is an empty list that gets filled with the devices
if item == device_data[-1]: //an if statement that will fill my last index in the list with all the devices that i want send forward to the webserver
print("MAC LIST------------>")
print("JSON LIST------------>")
new_mac_json = json.dumps(mac_list)
final_list = new_mac_json[2:-2] / i use this function to erase the bars from the list
print("NEW LIST------------>")
print(final_list )
json_obj_go = {
"data1": str,
"data2": int(time.time()),
"devices": {final_list // i put the list inside of the json body
}
}
print("JSON OBJ------------>")
print(json_obj_go)
输出看起来几乎很好,它只是在请求正文中的最终列表之前和之后结束的“'”。正如我之前所说,我希望设备元素内部有单独的设备,在数组中包含它们自己的特定值/数据
解决方案
推荐阅读
- node.js - 使用 Node.js 通过 json 中的变量插入值
- uml - 更好的 UML 类图结构来表示个人的婚姻
- sql - Oracle:事务表中的新用户计数
- autohotkey - 如何使用 AHK 发送正斜杠
- c++ - 使用复制构造函数 C++ 时出现分段错误
- python - 带有 URL 路径变量的 Python http 删除请求
- ionic-framework - 检查是否通过其 id 打开了任何模态,然后关闭该模态 IONIC
- python - QWebEnginePage 与 javascript 交互不起作用?
- mongodb - 通过 pymongo 如何将许多记录批量插入到不同的集合中
- reactjs - 未定义的 React-Native TypeError