gpt4 book ai didi

python - Django读取JSON文件

转载 作者:行者123 更新时间:2023-11-29 14:11:28 27 4
gpt4 key购买 nike

我有一个由 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com