代码之家  ›  专栏  ›  技术社区  ›  Tri

python将函数返回到json[关闭]

  •  -3
  • Tri  · 技术社区  · 7 年前

    我是使用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
    

    输出文件应该如下所示:

    {"Stuff":{
        "id":84576454,
        "name":"Shoes",
        "cost":431200,
        "color_and_size": {
            "color": {
                "brown":["XL", "XXL", "M"],
                "green":["XXL"]
            }
        }
    }
    }
    

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   notjoshno Deathsidious    7 年前

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

    load()加载一个json格式的 文件 并返回python dictionary>对象。

    jason.loads()返回json格式的python字典对象 一串 .

    dump()返回一个json格式的 文件 从python字典 对象

    json.dumps()返回一个json格式的 一串 从巨蟒身上 Dictionary对象

    所以你可以使用:

    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})