python的JSON响应打印问题



我正在击中API以根据数据库传递的参数获取ID,下面仅显示API部分。我通过2列。如果两个列在数据库中都有数据,则命中API-1。如果只有第二列具有数据,则它通过API-1击中API-2。问题在于打印响应,因为两个API都有不同的结构。

API-1的漂亮结构:

"body": { "type1": { "id": id_data, "col1": "col1_data", "col2": "col2_data"} }

API-2的漂亮结构:

"body": { "id": id_data, "col2": "col2_data" }

Python代码: print (resp['body']['type1']['id'], resp['body']['type1']['col1'], resp['body']['type1']['col2'])

您可以看到结构是不同的,如果两个参数都发送,则"打印"起作用,但是当仅发送第二列作为参数时,它会失败。

创建一个慷慨处理两种情况的打印机:

id_data = "whatever"
data1 = {"body": { "type1": { "id": id_data, "col1": "col1_data", "col2": "col2_data"} }}
data2 = { "body": { "id": id_data, "col2": "col2_data"}}
def printit(d):
    # try to acces d["body"]["type1"] - fallback to d["body"] - store it
    myd = d["body"].get("type1",d["body"])
    did = myd.get("id")      # get id
    col1 = myd.get("col1")   # mabye get col1
    col2 = myd.get("col2")   # get col2
    # print what is surely there, check for those that might miss
    print(did)
    if col1: 
        print(col1)
    print(col2 + "n") 

printit(data1)
printit(data2)

输出:

# data1
whatever
col1_data
col2_data
# data2
whatever
col2_data

最新更新