在烧瓶中发布多个对象JSON对象

时间:2018-04-26 04:44:50

标签: python json flask

我对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)

1 个答案:

答案 0 :(得分:2)

在这个json中

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

您有两组相同的密钥(“年龄”和“性别”),因此json序列化程序将获取每个重复密钥的最后一个值。(请参阅此链接:split)。也许您可以使用这种格式,也可以将年龄和性别属性组合在一起(例如:女性是4岁)

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