首页 > 解决方案 > 在烧瓶中发布多个 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)

标签: pythonjsonflask

解决方案


在这个 json

"members": [
      {
        "age": 4, 
        "gender": "female"
        "age" : 22
        "gender" : "male"
      }
    ]

您有两组相同的键(“年龄”和“性别”),因此 json 序列化程序将采用每个重复键的最后一个值。(请参阅此链接:JSON 对象中的重复键)。也许您可以改用这种格式,它将年龄和性别属性组合在一起(例如:女性 4 岁)

"members": [
          {
            "age": 4, 
            "gender": "female"
           },
           {
            "age" : 22
            "gender" : "male"
          }
        ]

推荐阅读