Opened 5 years ago

Closed 5 years ago

#29963 closed New feature (wontfix)

JsonField should not allows top-level scalar values

Reported by: Khashayar Owned by: nobody
Component: contrib.postgres Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hello,

There is an issue in JsonField validator.

It can validate a number instead of key/value format.

I read its source code and I understand it's for json.dumps() because it encodes python data structure to JSON format so it converts a number to string and it does not throw an exception as TypeError so JsonField validator accepts a number as a correct format and insert it in the database.

json.dumps(30)

output is : '30'

Change History (1)

comment:1 by Simon Charette, 5 years ago

Component: Database layer (models, ORM)contrib.postgres
Resolution: wontfix
Status: newclosed
Summary: JsonField validates number as a valid json formatJsonField should not allows top-level scalar values
Type: BugNew feature
Version: 1.11master

Python integers that are serialized to JSON numbers are valid JSON scalar values just like strings.

I assume you requesting that only JSON objects should be allowed to be provided for top level values for contrib.postgres.JsonField. If that's your request I'm afraid that it would be backward incompatible. It shouldn't be too hard to subclass JsonField or provide a validator to prevent JSON scalar and array equivalent values from being provided.

def validate_dict(value):
    if not isinstance(value, dict):
        raise ValidatorError('...')

class Foo(models.Model):
    data = JsonField(validators=[validate_dict])

I'll close this ticket as wontfix because of the backward compatibility concerns and the small amount of code required to achieve it using standard APIs. Feel free to re-open the ticket if I misunderstood your request.

Note: See TracTickets for help on using tickets.
Back to Top