用于api发布python的嵌套json语法

时间:2018-01-14 00:39:30

标签: python json

我正在尝试格式化我的json以发布到api,我不能为我的生活看到我的语法关闭或找到一个体面的参考来检查它是否100%正确。

下面是我的代码,它似乎在收件人部分失败了(我从下面的错误代码猜测)

statusCode“:400,”error“:”无效的参数:recipient.state“

我刚刚打印了json.dump,状态正确转换为两个字母。我甚至试图在一个让我相信它是json格式的语法的状态下进行编码。

@app.route('/printlab', methods=['POST'])
def printlab():
 if request.method == 'POST':
     lfname = request.form['first_name']
     llname = request.form['last_name']
     fullstate = request.form['state']
     lstate = us_state_abbrev.get(fullstate)
     lcity = request.form['city']
     laddress = request.form['shipping_address']
     lzip = request.form['zip']
     llb = request.form['lbs']
     loz = request.form['ozs']
     lw = (int(llb)*16)
     headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
     labela = {
        "authToken": vipkey,
        "labelType": "domestic",
         "mailClass": "MediaMail",
         "weightOz": lw,
         "description": "Books and Comics",
         "sender": [
            {"firstName": sfname},
            {"lastName": slname},
            {"streetAddress": saddress},
            {"city": scity},
            {"state": sstate},
            {"postalCode": spostcode}
                    ],
         "recipient": [
            {"state": lstate},
            {"firstName": lfname},
            {"lastName": llname},
            {"streetAddress": laddress},
            {"city": lcity},
            {"postalCode": lzip}
                        ]
                }

     r = requests.post(lurl, data=json.dumps(labela), headers=headers)
     return r.text
     #return lstate
 else:
     return """<html><body><h1>No Post data homeslice</h1></body></html>"""

下面是api所期望的json。

{
"authToken": "KEY",
"labelType": "domestic",
"mailClass": "Priority",
"weightOz": "16",
"description": "Test Dev",
"sender": {
    "firstName": "Test",
    "lastName": "Dev",
    "streetAddress": "100 Holomoana St",
    "city": "Philadelphia",
    "state": "PA",
    "postalCode": "96815"
},
"recipient": {
    "state": "NY",
    "firstName": "Test",
    "lastName": "Dev,
    "streetAddress": "11070 Glacier Hwy.",
    "city": "New York",
    "postalCode": "99801"
 }
}

任何事都将不胜感激!到目前为止,大约两天的头部猛烈抨击。

1 个答案:

答案 0 :(得分:0)

我的语法错了。这就是解决它的原因。

labela = {
        "authToken": vipkey,
        "labelType": "domestic",
         "mailClass": "MediaMail",
         "weightOz": lw,
         "description": "Books and Comics",
         "sender": {
            "firstName": sfname,
            "lastName": slname,
            "streetAddress": saddress,
            "city": scity,
            "state": sstate,
            "postalCode": spostcode
                    },
         "recipient": {
            "state": lstate,
            "firstName": lfname,
            "lastName": llname,
            "streetAddress": laddress,
            "city": lcity,
            "postalCode": lzip
                      }
                }