0

I am using json.dumps to display my object in json format.

My object

class Listing(object):
    name = ""
    introduction = ""
    products = []

class MenuItem(object):
    name = ""

new_listing = Listing()
new_listing.introduction = "this is my intro"
menuitem1 = MenuItem()
menuitem1.name = "product 1"
new_listing.products.append(menuitem1)
jsonstr = json.dumps(new_listing.__dict__, indent=4, separators=(". ", " = "))
print(jsonstr)

Output

{
    "introduction" = "this is my intro"
}

May I ask how do I get listing.products to appear in json

Master
  • 2,038
  • 2
  • 27
  • 77
  • Why is `Listing.products` a class variable instead of an instance variable? Are you not aware of the difference? – user2357112 Aug 10 '20 at 03:49
  • @user2357112supportsMonica would that make a difference with showing products or not? – Master Aug 10 '20 at 03:57
  • For my clarity, shouldn't the code be `new_listing.products.append(menuitem1.name)`and not `(menuitem1)`. And to dump json, you need to give `jsonstr = json.dumps(new_listing.products, indent=4, separators=(". ", " = "))` – Joe Ferndz Aug 10 '20 at 04:25
  • @JoeFerndz not at all, that's an array of strings, not an array of menuitems. – Master Aug 10 '20 at 13:16

1 Answers1

1

the following code works for me.

for more info about python json lib visit this web site https://pynative.com/make-python-class-json-serializable/

import json
from json import JSONEncoder

class Listing(object):
    def __init__(self):
        self.name = ""
        self.introduction = ""
        self.products = []


class MenuItem(object):
    def __init__(self, name):
        self.name = name

class ItemList(JSONEncoder):
    def default(self, o):
        return o.__dict__
    
new_listing = Listing()
new_listing.introduction = "this is my intro"

menuitem1 = MenuItem("product 1")

new_listing.products.append(menuitem1)

jsonstr = json.dumps(new_listing, indent=4, separators=(". ", " = "), cls=ItemList)

print(jsonstr)

output:

{
    "name" = "". 
    "introduction" = "this is my intro". 
    "products" = [
        {
            "name" = "product 1"
        }
    ]
}