我正在将JSON数据加载到“我的数据库”中,但给我错误-
TypeError - the JSON object must be str, not 'list'
from django.shortcuts import render
# Create your views here.
import json
from .models import Movie
def detail(request):
with open('movie_data.json', encoding='utf-8') as data_file:
json_data = json.loads(data_file.read())
print(type(json_data))
json_dict = json.loads(json_data)
for movie_data in json_dict:
movie = Movie.create(**movie_data)
# movie and genres created
Json文件-movie_data.json
[
{
"99popularity": 83.0,
"director": "Victor Fleming",
"genre": [
"Adventure",
" Family",
" Fantasy",
" Musical"
],
"imdb_score": 8.3,
"name": "The Wizard of Oz"
},
{
"99popularity": 88.0,
"director": "George Lucas",
"genre": [
"Action",
" Adventure",
" Fantasy",
" Sci-Fi"
],
"imdb_score": 8.8,
"name": "Star Wars"
},
]
我认为json应该转换为字典。我怎样才能做到这一点。我不知道是什么问题。我正在读取json文件。应该是字符串文件吗?
答案 0 :(得分:4)
您不需要致电json.loads()
两次。删除第二个呼叫。
答案 1 :(得分:1)
如上所述,json.loads()
不需要两次。并且当您在json_data = json.loads(data_file.read())
使用它时,它会被构造成词典列表。