Using JSON in Python

I am looking through the json documentation , and I am trying to figure out how to actually convert a Python object to JSON data, and then convert that data back to a Python object. I understand that you can pass lists, dicts and tuples of "primitives", as in the example above, but I tried to create a very minimal object and pass it to json.dumps () and got the "object is not JSON serializable".

What is the correct way to make a JSON object serializable? Currently, I imagine a method that converts my object into a dictionary, then passes it to json.dump () and a parallel method to take a dictionary and build a new object from it. However, this seems really redundant and limited, so I feel like something is missing. Can someone help me?

+1
source share
2 answers

Take a look at load()and dump(); each takes a functionobject_hook to decode and encode objects that are not usually JSONable. Perhaps this will be for you.

0
source

JSON Python 3. JSONEncoder decimal datetime.

import json
from decimal import Decimal
from datetime import datetime, date

class JSONEncoder(json.JSONEncoder):
  def default(self, o):
    if isinstance(o, Decimal):
      return float(o)
    elif isinstance(o, (datetime, date)):
      return o.isoformat()
    return super().default(self,o)

class JSONDecoder(json.JSONDecoder):
  pass

_Default_Encoder = JSONEncoder(
  skipkeys=False,
  ensure_ascii=False,
  check_circular=True,
  allow_nan=True,
  indent=None,
  separators=None,
  default=None,
  )

_Default_Decoder = JSONDecoder(
  object_hook=None, 
  object_pairs_hook=None
  )

Encode = _Default_Encoder.encode
Decode = _Default_Decoder.decode
0

Source: https://habr.com/ru/post/1789925/


All Articles