python - 在烧瓶中发布多个 JSON 对象
问题描述
我对 Web 开发领域还很陌生,我正在尝试弄清楚是否可以使用 curl X POST 从一个 request.json 对象中创建两个帖子。例如,如果我输入
curl -i -H "Content-Type: application/json" -X POST -d '{"income":500, "age" : 4, "gender" : "male"}' http://localhost:5000/house
进入命令行。我明白了
[
{
"income": 500.0,
"members": [
{
"age": 22,
"gender": "male"
}
],
"unique_id": 0
},
{
"income": 500.0,
"members": [
{
"age": 4,
"gender": "male"
}
],
"unique_id": 1
}
]
作为输出。我想要做的是获取另一个成员(年龄和性别 JSON 对象),我尝试过像这样使用 curl X POST
curl -i -H "Content-Type: application/json" -X POST -d '{"income":500, "age" : 4, "gender" : "female", "age" : 22, "gender" : "male"}' http://localhost:5000/house
并且输出应该看起来像
[
{
"income": 500.0,
"members": [
{
"age": 22,
"gender": "male"
}
],
"unique_id": 0
},
{
"income": 500.0,
"members": [
{
"age": 4,
"gender": "female"
"age" : 22
"gender" : "male"
}
],
"unique_id": 1
}
]
但相反,我得到
[
{
"income": 500.0,
"members": [
{
"age": 22,
"gender": "male"
}
],
"unique_id": 0
},
{
"income": 500.0,
"members": [
{
"age": 22,
"gender": "male"
}
],
"unique_id": 1
}
]
如您所见,它只发布我输入的最后一个 JSON 年龄和性别对象。有什么办法可以解决这个问题,所以它会同时发布年龄和性别 JSON 对象。我的代码如下。谢谢。
households = []
@app.route('/house', methods=['POST'])
def post_household():
"""this here gives us our unique id by counting the number of household objects
we have in our households list"""
unique_id = len(households)
house = Household({
'unique_id' : unique_id,
'income': request.json['income'],
'members':[
{
'age': request.json['age'],
'gender': request.json['gender']
},
]})
"""turns the Household object back into a dictionary so it can be jsonified"""
return_to_dictionary = house.to_primitive()
"""append our newly created dictionary to our households list"""
households.append(return_to_dictionary)
return jsonify(households)
解决方案
在这个 json
"members": [
{
"age": 4,
"gender": "female"
"age" : 22
"gender" : "male"
}
]
您有两组相同的键(“年龄”和“性别”),因此 json 序列化程序将采用每个重复键的最后一个值。(请参阅此链接:JSON 对象中的重复键)。也许您可以改用这种格式,它将年龄和性别属性组合在一起(例如:女性 4 岁)
"members": [
{
"age": 4,
"gender": "female"
},
{
"age" : 22
"gender" : "male"
}
]
推荐阅读
- javascript - 将数组映射到以奇数元素为键、偶数元素为值的对象
- c++ - 如何检查 pkg_check_modules 在哪里找到模块?
- java - 从保险库中提取数据库机密以执行 Jooq 不在本地主机上工作
- python - 在 Keras 中使用自定义步骤激活函数会导致“一个操作对梯度没有 `None`”。错误。如何解决这个问题?
- google-analytics - 仅在预览/调试模式下触发的自定义 HTML 标记
- node.js - UnityWebRequest.Post() multipart/form-data 不会将文件附加到自身
- javascript - react-admin 中是否有缓存
- d3.js - Hexbin 未在地理图块地图 D3.JS 上显示
- java - 在 Jetty 服务器中部署项目期间发生 BeanCreationException
- node.js - 在 Amazon Lambda 上公开多个端口/Express 应用程序