我很难弄清楚如何在循环内部为API创建JSON有效负载。
我可以从这里提取我需要的所有信息:
response_payload = response.json()
for client in response_payload['user_defined']:
name = client.get("name")
value = client.get("value")
required = client.get("required")
active = client.get("active")
在这个循环中,我想将这些变量添加到以下JSON:
{
name: {
"value": value,
"required": required,
"active": active
}
}
我不确定要在循环中添加什么来获取每个对象。例如:
payload = {
"property_1": {
"value": "string",
"required": true,
"active": true
},
"property_2": {
"value": "string",
"required": true,
"active": true
},
"property_3": {
"value": "string",
"required": true,
"active": true
}
}
任何帮助将不胜感激,如果我需要重新措辞更好地理解,请让我知道。谢谢你!
根据我的理解,这应该会给您预期的结果
import json
功能代码payload = dict()
for client in response_payload.get('user_defined', []):
name = client.get("name")
value = client.get("value")
required = client.get("required")
active = client.get("active")
payload[name] = {'value': value, 'required': required, 'active': active}})
print(json.dumps(payload, indent=4, sort_keys=True))
import json
payload = dict()
for client in response_payload.get('user_defined', []):
name = client.get("name")
value = client.get("value")
required = client.get("required")
active = client.get("active")
payload[name] = {'value': value, 'required': required, 'active': active}})
print(json.dumps(payload, indent=4, sort_keys=True))