Python的JSON响应打印问题

时间:2019-02-20 22:04:58

标签: json python-3.x api parsing printing

我正在根据从数据库传递的参数来敲击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'])

如您所见,结构是不同的,如果同时发送了两个参数,则'print'有效,但是当仅将第二列作为参数发送时,它将失败。

1 个答案:

答案 0 :(得分:0)

创建一个可以轻松处理这两种情况的打印机:

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