or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# jsonfield

1

2

A reusable Django model field that allows you to store validated JSON data in your model. jsonfield provides JSONField and JSONCharField classes that handle JSON serialization, deserialization, validation, and basic Django ORM integration for JSON data.

3

4

**Note**: This package is deprecated as Django 3.1+ includes native JSONField support. Use Django's built-in `models.JSONField` for new projects.

5

6

## Package Information

7

8

- **Package Name**: jsonfield

9

- **Language**: Python

10

- **Installation**: `pip install jsonfield`

11

- **Dependencies**: Django >= 4.2, Python >= 3.10

12

13

## Core Imports

14

15

```python

16

from jsonfield import JSONField, JSONCharField

17

```

18

19

Individual imports:

20

21

```python

22

from jsonfield import JSONField

23

from jsonfield import JSONCharField

24

```

25

26

Alternative submodule imports:

27

28

```python

29

from jsonfield import fields

30

from jsonfield.fields import JSONField, JSONCharField

31

from jsonfield.json import JSONString, checked_loads

32

from jsonfield.encoder import JSONEncoder

33

```

34

35

## Basic Usage

36

37

```python

38

from django.db import models

39

from jsonfield import JSONField, JSONCharField

40

41

class MyModel(models.Model):

42

# Basic JSON field (unlimited length)

43

data = JSONField()

44

45

# JSON field with default value

46

settings = JSONField(default={'theme': 'light', 'lang': 'en'})

47

48

# JSON field with length constraint

49

small_data = JSONCharField(max_length=255)

50

51

# Nullable JSON field

52

optional_data = JSONField(null=True, blank=True)

53

54

# Usage in views/code

55

obj = MyModel.objects.create(

56

data={'user_id': 123, 'preferences': ['dark_mode', 'notifications']},

57

settings={'theme': 'dark'},

58

small_data={'status': 'active'},

59

optional_data=None

60

)

61

62

# Access the data

63

print(obj.data['user_id']) # 123

64

print(obj.settings['theme']) # 'dark'

65

```

66

67

## Capabilities

68

69

### JSONField

70

71

Primary Django model field for storing JSON data without length constraints. Built on TextField with JSON serialization/deserialization.

72

73

```python { .api }

74

class JSONField(models.TextField):

75

"""

76

JSONField is a generic textfield that serializes/deserializes JSON objects.

77

78

Parameters:

79

- dump_kwargs (dict, optional): JSON serialization options passed to json.dumps()

80

- load_kwargs (dict, optional): JSON deserialization options passed to json.loads()

81

- All standard Django field parameters (null, blank, default, etc.)

82

"""

83

84

def __init__(self, *args, dump_kwargs=None, load_kwargs=None, **kwargs): ...

85

def to_python(self, value): ...

86

def from_db_value(self, value, expression, connection): ...

87

def get_prep_value(self, value): ...

88

def value_to_string(self, obj): ...

89

def formfield(self, **kwargs): ...

90

def get_default(self): ...

91

92

# JSONField-specific formfield enhancement

93

def formfield(self, **kwargs):

94

"""

95

Returns form field with enhanced defaults for TextArea widget.

96

Automatically sets 'indent': 4 and 'ensure_ascii': False for better formatting.

97

"""

98

```

99

100

#### Usage Examples

101

102

```python

103

from collections import OrderedDict

104

from jsonfield import JSONField

105

106

class ConfigModel(models.Model):

107

# Basic usage

108

config = JSONField()

109

110

# With default value

111

settings = JSONField(default={'enabled': True})

112

113

# With custom JSON serialization (pretty printing)

114

pretty_config = JSONField(

115

dump_kwargs={'indent': 4, 'ensure_ascii': False}

116

)

117

118

# Preserve key order with OrderedDict

119

ordered_config = JSONField(

120

load_kwargs={'object_pairs_hook': OrderedDict}

121

)

122

123

# Custom encoder for special data types

124

complex_data = JSONField(

125

dump_kwargs={'cls': MyCustomEncoder},

126

load_kwargs={'object_hook': my_decoder_function}

127

)

128

```

129

130

### JSONCharField

131

132

Character-based Django model field for storing JSON data with length constraints. Built on CharField with JSON serialization/deserialization.

133

134

```python { .api }

135

class JSONCharField(models.CharField):

136

"""

137

JSONCharField is a generic CharField that serializes/deserializes JSON objects.

138

139

Parameters:

140

- max_length (int): Maximum length of the JSON string representation

141

- dump_kwargs (dict, optional): JSON serialization options passed to json.dumps()

142

- load_kwargs (dict, optional): JSON deserialization options passed to json.loads()

143

- All standard Django CharField parameters

144

"""

145

146

def __init__(self, max_length, *args, dump_kwargs=None, load_kwargs=None, **kwargs): ...

147

```

148

149

#### Usage Examples

150

151

```python

152

class CompactModel(models.Model):

153

# Small JSON data with length constraint

154

status = JSONCharField(max_length=100, default={'active': True})

155

156

# Short configuration strings

157

settings = JSONCharField(max_length=255)

158

```

159

160

### Form Field Integration

161

162

Django form field for JSON input validation and handling in web forms.

163

164

```python { .api }

165

class JSONField(forms.CharField):

166

"""

167

Form field for JSON input validation.

168

169

Parameters:

170

- dump_kwargs (dict, optional): JSON serialization options

171

- load_kwargs (dict, optional): JSON deserialization options

172

- All standard Django CharField parameters

173

"""

174

175

def to_python(self, value): ...

176

def bound_data(self, data, initial): ...

177

def prepare_value(self, value): ...

178

```

179

180

### JSON Utilities

181

182

Helper functions and classes for JSON processing.

183

184

```python { .api }

185

def checked_loads(value, **kwargs):

186

"""

187

Safe JSON loading that prevents double-loading.

188

189

Parameters:

190

- value: Value to load (str, list, dict, int, float, JSONString, or None)

191

- **kwargs: Additional arguments for json.loads

192

193

Returns:

194

- Parsed Python object or original value if already loaded

195

"""

196

197

class JSONString(str):

198

"""

199

Marker class to differentiate loaded from unloaded JSON strings.

200

Inherits from str but indicates the string has been JSON-loaded.

201

"""

202

203

class JSONEncoder(json.JSONEncoder):

204

"""

205

Extended JSON encoder supporting Django model types.

206

207

Supports:

208

- datetime.datetime, datetime.date, datetime.time, datetime.timedelta

209

- decimal.Decimal, uuid.UUID

210

- Django QuerySet, Promise objects

211

- bytes, numpy arrays (if available)

212

- Iterables and mappings

213

"""

214

215

def default(self, obj): ...

216

217

# Constants

218

DEFAULT_DUMP_KWARGS = {'cls': JSONEncoder}

219

DEFAULT_LOAD_KWARGS = {}

220

```

221

222

### Configuration Options

223

224

#### Null Value Handling

225

226

Controls how null values are stored and queried:

227

228

```python

229

class MyModel(models.Model):

230

# null=True: nulls stored as database NULL, supports isnull lookup

231

nullable_json = JSONField(null=True, blank=True)

232

233

# null=False: nulls stored as JSON "null" string

234

non_nullable_json = JSONField(null=False)

235

236

# Querying

237

MyModel.objects.filter(nullable_json=None) # Works for both

238

MyModel.objects.filter(nullable_json__isnull=True) # Only works with null=True

239

```

240

241

#### Custom JSON Processing

242

243

```python

244

import json

245

from collections import OrderedDict

246

247

class CustomEncoder(json.JSONEncoder):

248

def default(self, obj):

249

if isinstance(obj, complex):

250

return {'__complex__': True, 'real': obj.real, 'imag': obj.imag}

251

return super().default(obj)

252

253

def complex_decoder(dct):

254

if '__complex__' in dct:

255

return complex(dct['real'], dct['imag'])

256

return dct

257

258

class MyModel(models.Model):

259

# Custom encoder/decoder

260

complex_data = JSONField(

261

dump_kwargs={'cls': CustomEncoder},

262

load_kwargs={'object_hook': complex_decoder}

263

)

264

265

# Preserve key ordering

266

ordered_data = JSONField(

267

load_kwargs={'object_pairs_hook': OrderedDict}

268

)

269

270

# Pretty printing for readability

271

readable_data = JSONField(

272

dump_kwargs={'indent': 4, 'ensure_ascii': False}

273

)

274

```

275

276

## Types

277

278

```python { .api }

279

class JSONFieldMixin(models.Field):

280

"""

281

Base mixin providing core JSON field functionality.

282

283

Attributes:

284

- form_class: Associated form field class

285

- dump_kwargs: JSON serialization options

286

- load_kwargs: JSON deserialization options

287

"""

288

289

form_class = forms.JSONField

290

291

def __init__(self, *args, dump_kwargs=None, load_kwargs=None, **kwargs): ...

292

def deconstruct(self): ...

293

def to_python(self, value): ...

294

def from_db_value(self, value, expression, connection): ...

295

def get_prep_value(self, value): ...

296

def value_to_string(self, obj): ...

297

def formfield(self, **kwargs): ...

298

def get_default(self): ...

299

300

class InvalidJSONInput(str):

301

"""

302

Marker class for invalid JSON input in forms.

303

Used internally to handle form validation errors.

304

"""

305

```

306

307

## Error Handling

308

309

The package handles several error conditions:

310

311

- **ValidationError**: Raised for invalid JSON in model fields during validation

312

- **json.JSONDecodeError**: Handled internally with runtime warnings for corrupted database data

313

- **ValueError**: Converted to ValidationError for timezone-aware datetime objects

314

315

```python

316

from django.forms import ValidationError

317

318

# Invalid JSON will raise ValidationError

319

try:

320

field.to_python('{"invalid": json}')

321

except ValidationError as e:

322

print(e.message) # "Enter valid JSON."

323

```

324

325

## Migration from Django's JSONField

326

327

For projects migrating to Django's native JSONField:

328

329

1. Replace imports: `from django.db import models``models.JSONField`

330

2. Update field definitions: `JSONField()``models.JSONField()`

331

3. Run migrations: `python manage.py makemigrations && python manage.py migrate`

332

4. For complex migrations, use data migrations to preserve field behavior differences