我有一组 ndJOSN 数据集,如下所示:
{'ADDRESS_CITY': 'Whittier', 'ADDRESS_LINE_1': '905 Greenleaf Avenue', 'ADDRESS_STATE': 'CA', 'ADDRESS_ZIP': '90402',},
{'ADDRESS_CITY': 'Cedar Falls', 'ADDRESS_LINE_1': '93323 Maplewood Dr', 'ADDRESS_STATE': 'CA', 'ADDRESS_ZIP': '95014'}
我需要将上面的值传递给 api 请求,特别是下面格式的正文。
data=[
{
"addressee":"Greenleaf Avenue",
"street":"905 Greenleaf Avenue",
"city":"Whittier",
"state":"CA",
"zipcode":"90402",
},
{
"addressee":"93323",
"street":"Maplewood Dr",
"city":"Cedar Falls",
"state":"CA",
"zipcode":"95014",
}
]
如您所见,密钥不同,因此我需要更改密钥以与正确的数据对齐并使用新的密钥名称传递它们(即 address_line_1 发送给收件人) - 此请求中将有 10k 个地址.
在我的第一个示例中我没有注意到它,但是每个地址都有一个关联的 ID - 我必须删除才能发出请求,然后重新添加。所以我最终用下面的方法解决了 - 任何更多的 Pythonic,这些感觉对我来说不是那么雄辩……?
addresses = ndjson.loads(addresses)
data = json.loads(json.dumps(addresses).replace('"ADDRESS_CITY"','"city"').replace('"ADDRESS_LINE_1"','"street"').replace('"ADDRESS_STATE"','"state"').replace('"ADDRESS_ZIP"','"zipcode"'))
ids = []
for i in data:
i['candidates'] = 1
ids.append(i["ID"])
del i["ID"]
response = requests.request("POST", url, json=data)
resp_data = response.json()
a = 0
for i in resp_data:
i['ID'] = ids[a]
x = i['ID'] = ids[a]
a = a + 1