使用for循环创建多个json对象

时间:2020-05-09 17:59:01

标签: python json

我正在创建一个计费系统,需要从我的API中输出一些数据。我想将数据作为JSON返回,但是即使有多个,我也只能在输出中获取数据库条目之一。我坚信我会覆盖我之前的条目。

当前输出为:

{
   "id":2,
   "status":"active",
   "usage_type":"metered",
   "amount":0,
   "city":"Parkinson",
   "country":"UK",
   "line1":"Silverway 30",
   "postal_code":"4450",
   "state":"state",
   "card_brand":"visa",
   "card_country":"US",
   "card_exp_month":3,
   "card_exp_year":2025,
   "card_last4":"4242"
}

但是它从我的数据库中丢失了"id":1,我认为这是因为我覆盖了之前的内容。

我想要的输出应如下所示:

{
   "id":1 {
       "status":"active",
       "usage_type":"metered",
       "amount":0,
       "city":"Parkinson",
       "country":"UK",
       "line1":"Silverway 1",
       "postal_code":"0030",
       "state":"state",
       "card_brand":"visa",
       "card_country":"US",
       "card_exp_month":3,
       "card_exp_year":2025,
       "card_last4":"4242"
},
 "id":2 {
       "status":"active",
       "usage_type":"metered",
       "amount":0,
       "city":"Parkinson",
       "country":"UK",
       "line1":"Silverway 20",
       "postal_code":"0330",
       "state":"state",
       "card_brand":"visa",
       "card_country":"US",
       "card_exp_month":3,
       "card_exp_year":2025,
       "card_last4":"4242"
},

我当前的代码:

@api_view(['GET',])
@permission_classes([IsAuthenticated])
def get_billing(request):
    """
    List current billing options
    """
    if request.method == 'GET':
        data = Customer.objects.filter(user=request.user)
        jsondata = {}
        for subscription in data:
            get_subscription = stripe.Subscription.retrieve(subscription.subscription_id)
            get_payment = stripe.PaymentMethod.retrieve(subscription.payment_method)
            jsondata["id"] = subscription.pk
            jsondata["status"] = get_subscription['status']
            jsondata["usage_type"] = get_subscription['plan']['usage_type']
            jsondata["amount"] = get_subscription['plan']['amount']
            jsondata['city'] = get_payment['billing_details']['address']['city']
            jsondata['country'] = get_payment['billing_details']['address']['country']
            jsondata['line1'] = get_payment['billing_details']['address']['line1']
            jsondata['postal_code'] = get_payment['billing_details']['address']['postal_code']
            jsondata['state'] = get_payment['billing_details']['address']['state']
            jsondata['card_brand'] = get_payment['card']['brand']
            jsondata['card_country'] = get_payment['card']['country']
            jsondata['card_exp_month'] = get_payment['card']['exp_month']
            jsondata['card_exp_year'] = get_payment['card']['exp_year']
            jsondata['card_last4'] = get_payment['card']['last4']
            json_data = json.dumps(jsondata)
        return Response(jsondata, status=status.HTTP_200_OK)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我在做什么错?让我知道是否需要提供更多信息。谢谢!

2 个答案:

答案 0 :(得分:0)

这里更多是一个可行的例子。这将形成对象图。如果还可以使用列表,但这在很大程度上取决于您的用例:

数据= [ { “ pk”:1 “ status”:“有效”, “计划”:“ PayAsYouGo” }, { “ pk”:2 “ status”:“无效”, “计划”:“ PayAsYouGo” }, ]

jsondata = {}

for subscription in data:
    json = {
        "status" : subscription['status'],
        "usage": subscription['plan']
    }

    jsondata[subscription['pk']] = json

print(jsondata)

{1: { '状态':'有效', '用法':'PayAsYouGo' }, 2:{ 'status':'invalid', '用法':'PayAsYouGo' } }

答案 1 :(得分:0)

您可能想返回一个列表。将列表包装在字典中通常是一个好主意,以防您以后要使用其他元数据(例如分页或其他内容)进行扩展。因此,{'items':[...]}

# ...
customers = Customer.objects.filter(user=request.user)
items = []
for customer in customers:
    subscription = stripe.Subscription.retrieve(customer.subscription_id)
    payment = stripe.PaymentMethod.retrieve(customer.payment_method)
    items.append({
        'id': customer.pk,
        'status': subscription['status'],
        # ... the rest of your data ...
    })
    # Next line does nothing...
    # json_data = json.dumps(jsondata)
return Response({'items': items})  # Status is 200 by default