Python返回JSON函数

2024-09-26 18:18:35 发布

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

我是JSON的初学者,现在我将使用Python。 最近我做了这样的代码:

import json


def product():
    itemId = 84576454
    itemName = 'FGX Flannel Shirt'
    price = 195000
    availableColorAndSize = {
        'color': {'blue-black': ['M', 'L', 'XL'],
                  'black-white': ['L']}
    }

    freeShiping = False

输出文件应该如下所示:

^{pr2}$

在我完成这个之前:Store Python function in JSON 但我仍然很困惑,不知道如何返回该函数来生成JSON。在


Tags: 代码importjsondefproductpriceblack初学者
1条回答
网友
1楼 · 发布于 2024-09-26 18:18:35

Python的内置JSON库可以为您做到这一点。四个主要功能如下:

json.load() loads a JSON formatted file and returns a Python dictionary >object.

json.loads() returns a Python dictionary object from a JSON formatted string.

json.dump() returns a JSON formatted file from a Python dictionary object

json.dumps() returns a JSON formatted string from a Python dictionary object

所以你可以使用:

import json


def product():
    itemId = 12341822
    itemName = 'FGX Flannel Shirt'
    price = 195000
    availableColorAndSize = {
        'color': {'blue-black': ['M', 'L', 'XL'],
                  'black-white': ['L']}
    }

    freeShiping = False

    # Returns a JSON formatted file based on the dictionary shown
    return json.dump(
        {'itemId': itemId,
         'itemName': itemName,
         'price': price,
         'availableColorAndSize': availableColorAndSize,
         'freeShiping': freeShiping})

相关问题 更多 >

    热门问题