#35525: Django error with parsing JSONField
-------------------------------------+-------------------------------------
     Reporter:  Nirjal Paudel        |                    Owner:  nobody
         Type:  New feature          |                   Status:  closed
    Component:  Database layer       |                  Version:  dev
  (models, ORM)                      |
     Severity:  Normal               |               Resolution:  wontfix
     Keywords:                       |             Triage Stage:
  Models,fields,encoding,decoding    |  Unreviewed
    Has patch:  0                    |      Needs documentation:  0
  Needs tests:  0                    |  Patch needs improvement:  0
Easy pickings:  0                    |                    UI/UX:  0
-------------------------------------+-------------------------------------
Comment (by Nirjal Paudel):

 Hi, thank-you for replying. Can you explain to me the `from_db_value`
 part, as I think the default decoder option I mean just making an
 exception for JSONField with json type and  psycopg2. How about the two
 code here. Sorry if this is stupid to ask

 {{{

 class DjangoJSONEncoder(json.JSONEncoder):
     """
     JSONEncoder subclass that knows how to encode date/time, decimal
 types, and
     UUIDs.
     """

     def default(self, o):
         # See "Date Time String Format" in the ECMA-262 specification.
         if isinstance(o, datetime.datetime):
             r = o.isoformat()
             if o.microsecond:
                 r = r[:23] + r[26:]
             if r.endswith("+00:00"):
                 r = r.removesuffix("+00:00") + "Z"
             return r
         elif isinstance(o, datetime.date):
             return o.isoformat()
         elif isinstance(o, datetime.time):
             if is_aware(o):
                 raise ValueError("JSON can't represent timezone-aware
 times.")
             r = o.isoformat()
             if o.microsecond:
                 r = r[:12]
             return r
         elif isinstance(o, datetime.timedelta):
             return duration_iso_string(o)
         elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)):
             return str(o)
         # how about adding 2 conditions here
        # one for list and dict to put it here
         elif isinstance(o, list):
             return o
         elif isinstance(o, dict):
             return o
         else:
             return super().default(o)

 }}}

 Replying to [comment:1 Simon Charette]:
 > > So I had a django JSONField table with column called logs which is a
 json field [ Not jsonb field ].
 >
 > Django doesn't support pointing fields designed to work with certain
 database data types to others, `JSONField` is not exception.
 >
 > > Instead of doing this, why don't we check if the content/value parsed
 from db is list or dict, by default python types for json
 > > If yes - Don't do anything
 > > If no and is a string instance - then perform json.loads() to it
 >
 > If you need this feature simply subclass `JSONField` and override it's
 `from_db_value` method. Note that if you use this approach you won't be
 able to implement support for the `decoder` option as this requires the
 decoding to be performed by the field itself and not from psycopg.
-- 
Ticket URL: <https://code.djangoproject.com/ticket/35525#comment:2>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/0107019016f02a6f-7a32258e-175f-4dca-a909-a2fcb06b8a7c-000000%40eu-central-1.amazonses.com.

Reply via email to