ngiachou / WalletHero

A hero we all deserve. Tracking your monthly costs was never been so much fun.
GNU General Public License v3.0
0 stars 0 forks source link

Implementation of an extended JSON encoder #11

Closed ngiachou closed 6 years ago

ngiachou commented 6 years ago

OK, so I've made two encoders actually. One works for Product instances and the other for Transaction instancies. There will be another encoder for PersonalBank instances when that class is implemented.

Essentially, the implementation calls the encoder of the top level and recursively calling encoders for lower level. For example, to encode a Transaction instance the encoder for that instance is called which in turn calls the encoder for every product in the product list.

Here is the testing code:

if __name__ == "__main__":
    p = pr.Product("Beer", 2.5)
    json_string = json.dumps(p, cls=ProductEncoder)

    pprint.pprint(json.loads(json_string))

    p2 = pr.Product("Pizza", 9.0)
    t = tr.Transaction([p, p2], "friends", "in", datetime.date.today())
    json_string = json.dumps(t, cls=TransactionEncoder)

    pprint.pprint(json.loads(json_string))

and here is the response:

{'name': 'Beer', 'price': 2.5}
{'date': '2018-10-11',
 'environment characteristic': 'friends',
 'place': 'in',
 'product list': [{'name': 'Beer', 'price': 2.5},
                  {'name': 'Pizza', 'price': 9.0}]}

notice that both json.loads() and json.dumps() are called. The former is for reading json strings and the latter for creating them. Hence, the whole cycle of read/write works. There is a catch though...

Loading a json string just makes it a dictionary which means that we still have to convert that into instances of the specific classes.

ngiachou commented 6 years ago

Now PesonalBank objects are json-serializable.

Testing output:

{
  "name": "Beer",
  "price": 2.5
}
{
  "date": "2018-10-29",
  "environment characteristic": "friends",
  "place": "in",
  "product list": [
    {
      "name": "Beer",
      "price": 2.5
    },
    {
      "name": "Pizza",
      "price": 9.0
    }
  ]
}
{
  "balance": 350,
  "history": [
    {
      "date": "2018-10-29",
      "environment characteristic": "friends",
      "place": "in",
      "product list": [
        {
          "name": "Beer",
          "price": 2.5
        },
        {
          "name": "Pizza",
          "price": 9.0
        }
      ]
    }
  ]
}