简体   繁体   English

如何将字典放入 JSON?

[英]How to put a dictionary in a JSON?

I'm working with a REST API, and I need to return a JSON with my values to it.我正在使用 REST API,我需要返回一个带有我的值的JSON However, I need the items of the payload variable to show all the items inside the cart_item .但是,我需要 payload 变量的items来显示cart_item内的所有项目。

I have this:我有这个:

payload = {
    "items": [],
}

I tried this, but I don't know how I would put this inside the items of the payload:我试过了,但我不知道如何将其放入有效负载的items中:

for cart_item in cart_items:
    item = [
        {
            "reference_id": f"{cart_item.sku}",
            "name": f"{cart_item.product.name}",
            "quantity": cart_item.quantity,
            "unit_amount": cart_item.product.price
        },
     ]

I need you to get back to me:我需要你回复我:


payload = {
    "items": [ 
        {
            "reference_id": "SKU49FS20DD",
            "name": "Produto 1",
            "quantity": 1,
            "unit_amount": 130
        },
        {
            "reference_id": "SKU42920SSD",
            "name": "Produto 2",
            "quantity": 1,
            "unit_amount": 100
        }
    ],
}

response = requests.request(
    "POST",
    url,
    headers=headers,
    json=payload
)

I don't know if I would need to pass what's in JSON to the dictionary to change and then send it to JSON again.我不知道我是否需要将JSON中的内容传递给字典进行更改,然后再次将其发送到JSON

You're just missing the " append() " method on a list, and the conversion from Python list & dict to a JSON string :您只是缺少列表上的“ append() ”方法,以及从Python 列表和字典到 JSON 字符串的转换:

 from json import dumps

 items_dict = []
 for cart_item in cart_items:
            items_dict.append({
                "reference_id": f"{cart_item.sku}",
                "name": f"{cart_item.product.name}",
                "quantity": cart_item.quantity,
                "unit_amount": cart_item.product.price
             })

payload = {
    'items': items_dict
}

# And if you want a JSON string as output
print(dumps(payload))

But you don't need a string to the "json" argument in requests.post, so you can keep your但是你不需要一个字符串到 requests.post 中的“json”参数,所以你可以保留你的

response = requests.request(
    "POST",
    url, 
    headers=headers,
    json=payload
)

Instead of trying to create one item at a time, just populate payload['items'] directly, using a comprehension:与其尝试一次创建一个项目,不如使用理解直接填充payload['items']

payload['items'] = [
    {
        'reference_id': cart_item.sku,
        'name': cart_item.product.name,
        'quantity': cart_item.quantity,
        'unit_amount': cart_item.product.price 
    }
    for cart_item in cart_items
]

Another possible improvement is about requests .另一个可能的改进是关于requests Instead of using requests.requests('POST'...) , you can use requests.post(...) .您可以使用requests.post(...)而不是使用requests.requests('POST'...) ) 。

And finally, if the API really needs json to have a valid JSON string, use json.dumps to convert it.最后,如果 API 确实需要json来获得有效的JSON字符串,请使用json.dumps进行转换。

Putting all together:放在一起:

import requests
import json

payload['items'] = [
    {
        'reference_id': cart_item.sku,
        'name': cart_item.product.name,
        'quantity': cart_item.quantity,
        'unit_amount': cart_item.product.price 
    }
    for cart_item in cart_items
]

response = requests.post(
    url,
    headers=headers,
    json=json.dumps(payload)
)

Even though I'm almost a hundred percent sure requests.post() will do the right thing if you just pass the payload as is in json=payload .即使我几乎百分百确定requests.post()会做正确的事情,如果你只是像json=payload payload传递有效负载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM