0

I am having some difficulties building JSON files out of fairly complex python objects.

The class which I am trying to build into a JSON file looks like this:

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

I tried building a dictionary where the keys were the string name of the attribute, and the values were the contents of the attribute. However, the json.dump() didn't like the dictionary of lists, dicts, and strings. Do I manually have to create the logic for populating the JSON file, such as creating a string by joining all the contents of a list and delimiting it in a unique way, or is there an easier way to translate such an object into JSON?

For reference, a populated Recipe object would look something like this:

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]

I'm stuck trying to turn this into JSON, and any help would be greatly appreciated!

Thank's in advance.

1 Answer 1

2

You will just need to use json module to dump the __dict__ attribute of the object. This words because you are using the object like a dictionary with the attributes as "keys" and assigning them the "value".

Assuming your class is built correctly (only a copy-and-paste error to SO) and recipe is an instance of Recipe, you can dump to json like this:

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

here is a simple working example:

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

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.