2017-04-20 66 views
0

我有一些困难,从相当复杂的python对象构建JSON文件。构建JSON文件的python对象

我正努力打造成为一个JSON文件中的类看起来是这样的:

class Recipe: 
def __ini__(self): 
    self.recipeTitle = "" 
    self.recipeDiscription = "" 
    self.recipeMetaData = [] 
    self.reipeIngredients = collections.OrderedDict() 
    self.instructions = [] 
    self.searchableIngredients = [] 
    self.allIng = [] 
    self.tags = [] 
    self.ingredientMetadata = [] 
    # self.getAllIngredients() 

我试图建立一个字典,其中键是属性的字符串名称,和值是内容属性。但是,json.dump()不喜欢列表,字典和字符串的字典。我是否需要手动创建填充JSON文件的逻辑,例如通过连接列表中的所有内容并以独特方式对其进行分隔来创建字符串,还是将此类对象转换为JSON更简单?

作为参考,填充配方对象会是这个样子:

recipe.recipeTitle = "Pancakes" 
recipe.recipeDiscription = "Something really tasty" 
recipe.metaData = ["15 Minutes", "Serves 5"] 
recipe.recipeIngredients = {('For the sauce', ['sugar', 'spice', 
'everything nice']),('For the food', ['meat', 'fish', 'eggs'])} 
recipe.instructions = ['First, stir really well', 'Second - fry'] 
self.allIng = ['sugar', 'spice', 'everything nice', 'meat', 'fish', 
'eggs'] 
self.tags = [1252, 2352, 2174, 454] 
self.ingredientMetadata = [1,17,23,55,153,352] 

我卡试图把它变成JSON和任何帮助将不胜感激!

提前致谢。

回答

1

您只需要使用json模块来转储对象的__dict__属性。这个词是因为你使用的对象就像一个字典,其属性是“键”,并赋予它们“值”。

假设你的类是否正确(仅进行复制和粘贴错误SO)和recipeRecipe一个实例,你可以转储到JSON是这样的:

import json 
print(json.dumps(recipe.__dict__, indent = 4)) 

这里是一个简单的工作例如:

import json 
class foo: 
    def __init__(self): 
     self.spam = 123 
     self.egg = "this is a string" 
     self.apple = ["a list with", 3, "values"] 
     self.banana = {"dicts" : ["and nested list", "also works", 00]} 
myfoo = foo() 
print(json.dumps(myfoo.__dict__, indent = 4)) 

试试:https://repl.it/HRSK/0