python - Django读取JSON文件

标签 python json django postgresql scrapy

我有一个由 scrapy 生成的以下格式的 json 文件:

[
    {
        "area_of_interest": [
            "Pharmaceutical"
        ], 
        "department": [
            "RETAIL PHARMACY: APOTHECARY"
        ], 
        "duties": [
            "EDUCATION:"
        ], 
        "job_function": [
            "Texas Health Presbyterian Hospital Dallas is seeking a Registered Pharmacy Technician to work PRN (as needed) hours in the Retail Pharmacy. Primary hours will be weekday shifts between 9a-5p. There will be occasional 12 hr shifts. The following is required:"
        ], 
        "job_id": [
            "  56345"
        ], 
        "job_type": [
            "PRN"
        ], 
        "location": [
            "Dallas, TX, US"
        ], 
        "location_type": [
            " Texas Health Dallas"
        ], 
        "relocation": [
            "No"
        ], 
        "shift": [
            "Variable"
        ], 
        "speciality": [
            "TCH"
        ], 
        "title": [
            "Pharmacy Tech (PRN) - Retail Pharmacy"
        ], 
        "travel": [
            "NN"
        ]
    },...

这是我的模型的样子:

class health(models.Model):
    location = models.CharField(max_length=32)
    title = models.CharField(max_length=64)
    location_type = models.CharField(max_length=32)
    job_id = models.CharField(max_length=16)
    department = models.CharField(max_length=24)
    area_of_interest = models.CharField(max_length=32)
    job_type = models.CharField(max_length=32)
    shift = models.CharField(max_length=32)
    relocation = models.CharField(max_length=8)
    travel = models.CharField(max_length=8)
    speciality = models.CharField(max_length=32)
    job_function = models.CharField(max_length=96)
    duties = models.CharField(max_length=56)

由于我是 Django 的新手,我引用了许多关于如何从 Django 读取 json 文件并将数据存储到 postgresql 数据库的帖子和博客。但是大多数帖子都与我不知道如何使用的 javascript 有关。

所以我的问题是,如何使用 django 从 json 文件中读取数据并将字段存储到 postgresql 数据库中?

提前致谢

最佳答案

参见内置文档 json引用模块如何解析 json 参见 bulk_create引用如何创建批量插入

示例代码(未经测试):

# Read file 
f = open('path_to_file.json')
json_string = f.read()
f.close()

# Convert json string to python object
import json
data = json.loads(json_string)

# Create model instances for each item
items = []
for item in data:
   # create model instances...
   item = YourModel(*item)
   items.append(item)

# Create all in one query
YourModel.objects.bulk_create(items)

关于python - Django读取JSON文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21858465/

相关文章:

python - 如何更正我的代码以生成嵌套字典?

python - gc 上的段错误,使用 ctypes

Python父类访问子类的类变量

ios - 使用 Codable 协议(protocol)仅解码 JSON 的一部分

java - 使用 GSON 解析 JSON 数组

django - Getting __init__() got an unexpected keyword argument 'instance' with CreateView of Django

python - 在本地主机上运行 python 脚本

c# - 在 C# 中从对象(反序列化的 json)中检索数据

python - Django UpdateView 创建新对象

django - 如何在 Django 1.9 中为同一个应用程序拥有单独的 url