【问题标题】:the JSON object must be str, not 'list' - TypeErrorJSON 对象必须是 str,而不是 'list' - TypeError
【发布时间】:2019-08-04 08:22:53
【问题描述】:

我正在我的数据库中加载 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 文件。应该是字符串文件吧?

【问题讨论】:

    标签: python json django python-3.x


    【解决方案1】:

    您无需致电json.loads() 两次。删除第二个调用。

    【讨论】:

      【解决方案2】:

      如上所述,json.loads() 没有必要两次。当你在json_data = json.loads(data_file.read()) 使用它时,它的结构是一个字典列表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多