【问题标题】:Python return function to JSON [closed]Python返回函数到JSON [关闭]
【发布时间】:2018-11-17 13:30:59
【问题描述】:

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

【问题讨论】:

  • “返回 JSON 文件” 到底是什么意思?您是否对 Python 处理 JSON 的功能进行了一些研究?
  • @jonrsharpe 返回 JSON 格式的值
  • 那么你的意思是作为一个字符串吗?
  • @jonrsharpe 是的,对.. 抱歉,但我在stackoverflow.com/questions/51936785/… 之前尝试过研究此代码
  • 花点时间浏览一下standard library。你永远不知道你可能会找到what

标签: python arrays json object


【解决方案1】:

Python's built-in JSON library 可以为您做到这一点。四个主要功能如下:

json.load() 加载一个 JSON 格式的 file 并返回一个 Python 字典 >object。

json.loads() 从 JSON 格式返回一个 Python 字典对象 字符串

json.dump() 从 Python 字典中返回 JSON 格式的 file 对象

json.dumps() 从 Python 返回 JSON 格式的 string 字典对象

所以你可以使用:

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

【讨论】:

  • 非常感谢@wiomoc,它的工作完美。
猜你喜欢
  • 1970-01-01
  • 2016-08-21
  • 2013-12-18
  • 1970-01-01
  • 2013-04-22
  • 2019-11-25
  • 2014-03-25
  • 1970-01-01
  • 2012-02-18
相关资源
最近更新 更多