2017-04-20 33 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