0

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 } ]

0

2 Answers 2

1

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

import json
your_json = json.loads(f.read())
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.