如何在Python中遍历“无名”JSON条目?

2024-09-28 22:22:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些来自HubSpot CRM API的JSON数据,在doing some pagination using Python Code之后基本上如下所示:

[
  {
    "dealId": 18039629,
    "portalId": 62515,
    "isDeleted": false
  },
  {
    "dealId": 18040854,
    "portalId": 62515,
    "isDeleted": false
  }
]

。。。现在我想做的是:

1)一次读取一组JSON(表示dealId、portalId、isDeleted)
2) 如果isDeleted==false,则抓取dealIdportalId并存储在变量中
3) 使用上面#2中的变量来构建URL字符串,该字符串可用于返回HubSpot API并获取每个交易的信息(此API端点是https://api.hubapi.com/deals/v1/deal/23487870?hapikey=demo(其中23487870是上面JSON中的dealId
4) 将单个交易级别的信息合并到另一组JSON中。具体来说,我想从JSON中获取/properties/dealname/valueproperties/dealstage/value,如下所示:

{
    "portalId": 62515,
    "dealId": 23487870,
    "isDeleted": false,
    "properties": {
        "dealname": {
            "value": "AutomationTestUser-national",
            "timestamp": 1457692022120
        },
        "dealstage": {
            "value": "appointmentscheduled",
            "timestamp": 1457692022120
        }
    },
    "imports": []
}

5)然后以JSON格式输出最终结果,如下所示:

{
    "deals":
    [
        {
            "portalId": 62515,
            "dealId": 23487870,
            "isDeleted": false,
            "properties": {
                "dealname": {
                    "value": "AutomationTestUser-national",
                    "timestamp": 1457692022120
                },
                "dealstage": {
                    "value": "appointmentscheduled",
                    "timestamp": 1457692022120
                }
            },
            "imports": []
        },
        {
            "portalId": 62515,
            "dealId": 23487871,
            "isDeleted": false,
            "properties": {
                "dealname": {
                    "value": "AutomationTestUser-regional",
                    "timestamp": 1457692022120
                },
                "dealstage": {
                    "value": "appointmentscheduled",
                    "timestamp": 1457692022120
                }
            },
            "imports": []
        }
    ]
}

。。。全是Python。你知道吗

有什么帮助吗?你知道吗


Tags: apijsonfalsevaluepropertiestimestampimportshubspot
1条回答
网友
1楼 · 发布于 2024-09-28 22:22:24
import json
output = {"deals": []}

data = """
[
  {
    "dealId": 18039629,
    "portalId": 62515,
    "isDeleted": false
  },
  {
    "dealId": 18040854,
    "portalId": 62515,
    "isDeleted": false
  }
]
"""

j = json.loads(data)
for deal in j:
    if deal['isDeleted']:
        continue              # Ignore if deleted
    dealId = deal['dealId']
    url = 'https://api.hubapi.com/deals/v1/deal/' + str(dealId) + '?hapikey=demo' # Construct new url here
    data = getSource(url) # implement getSource to perform web request and get data
    j2 = json.loads(data)
    output['deals'].append(j2)

print(output)

相关问题 更多 >