By Nurbek


2020-08-01 13:20:16 8 Comments

I have got when I want convert json data in django models. How can I solve it.

class Persons(models.Model):
rank = models.IntegerField()
employer = models.CharField(max_length=100)
employeesCount = models.IntegerField()
medianSalary = models.IntegerField()

object creater:

for json in json_string:
Persons.objects.create(id=json['rank'], employer=json['employer'], employeesCount=json['employeesCount'], medianSalary=json['medianSalary'])

json reader

f = open('data.json')
json_string = f.read()
f.close()

json file: [ { "rank": 1, "employer": "Walmart", "employeesCount": 2300000, "medianSalary": 19177 }, { "rank": 2, "employer": "Amazon", "employeesCount": 566000, "medianSalary": 38466 } ]

2 comments

@Willem Van Onsem 2020-08-01 13:27:59

Th json_strings is just a string, not a list of dictionaries. You can make use of the json module [python-doc] to JSON deserialize it:

from json import load as json_load

with open('data.json') as f:
    json_data = json_load(f)

Persons.objects.bulk_create([
    Person(
        id=record['rank'],
        employer=record['employer'],
        employeesCount=record['employeesCount'],
        medianSalary=record['medianSalary']
    )
    for record in json_data
])

By using bulk_create you create the objects in bulk in the database, which reduces the number of roundtrips to the database.

@Nurbek 2020-08-01 14:04:23

Thank! It works

@Márcio Carôso 2020-08-01 13:27:30

Your code is expecting a dictionary. Convert the json string using the builtin library

import json
your_json = json.loads(f.read())

Related Questions

Sponsored Content

15 Answered Questions

[SOLVED] Creating a JSON response using Django and Python

  • 2010-03-11 19:40:35
  • Switch
  • 513549 View
  • 462 Score
  • 15 Answer
  • Tags:   python django json

36 Answered Questions

[SOLVED] What is the correct JSON content type?

13 Answered Questions

[SOLVED] What's the canonical way to check for type in Python?

  • 2008-09-30 11:00:10
  • Herge
  • 900080 View
  • 1315 Score
  • 13 Answer
  • Tags:   python types

6 Answered Questions

[SOLVED] Post JSON using Python Requests

24 Answered Questions

[SOLVED] How do I POST JSON data with cURL?

16 Answered Questions

[SOLVED] How to determine a Python variable's type?

9 Answered Questions

[SOLVED] Why can't Python parse this JSON data?

  • 2010-05-14 15:54:20
  • michele
  • 2641643 View
  • 1447 Score
  • 9 Answer
  • Tags:   python json parsing

14 Answered Questions

[SOLVED] How do I write JSON data to a file?

  • 2012-09-06 22:21:21
  • user1530318
  • 1504295 View
  • 1169 Score
  • 14 Answer
  • Tags:   python json

1 Answered Questions

[SOLVED] django - inlineformset_factory with more than one ForeignKey

  • 2010-01-27 19:28:33
  • fabriciols
  • 2954 View
  • 9 Score
  • 1 Answer
  • Tags:   python django

2 Answered Questions

[SOLVED] Filtering models with inheritance in Django

Sponsored Content