You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django框架中使用Python读取JSON文件?

在Django中读取JSON文件的实用方法

Hey there! Reading a JSON file in Django is straightforward since Django is built on Python—you can leverage Python's built-in json module along with Django's project path utilities to do this cleanly. Let me walk you through a few solid approaches using your provided JSON data as an example.

1. 基础读取方式(核心思路)

First, you'll want to avoid hardcoding file paths (that's a recipe for bugs when deploying!). Use Django's settings.BASE_DIR to get your project's root directory, then build the path to your JSON file from there.

示例代码

Let's say your JSON file is named categories.json and lives in your project root. Here's how to read it:

import json
from django.conf import settings
import os

def load_category_data():
    # 构建JSON文件的绝对路径
    json_file_path = os.path.join(settings.BASE_DIR, 'categories.json')
    
    # 打开并解析文件
    with open(json_file_path, 'r') as json_file:
        category_data = json.load(json_file)
    
    # 现在你可以直接使用这个字典了
    print(category_data["Income"])  # 会输出: ["salary","deposit","rewards"]
    return category_data

2. 在Django视图中使用该数据

If you need to pass this JSON data to a template, you can load it directly in your view function:

from django.shortcuts import render
import json
from django.conf import settings
import os

def category_view(request):
    # 加载JSON数据
    json_path = os.path.join(settings.BASE_DIR, 'categories.json')
    with open(json_path, 'r') as f:
        categories = json.load(f)
    
    # 传递给模板
    return render(request, 'categories.html', {'category_groups': categories})

In your template (categories.html), you can loop through the data like any other dictionary:

{% for group, items in category_groups.items %}
    <h3>{{ group }}</h3>
    <ul>
        {% for item in items %}
            <li>{{ item }}</li>
        {% endfor %}
    </ul>
{% endfor %}

3. 加入异常处理(生产环境推荐)

It's smart to add error handling for common issues like missing files or invalid JSON:

def load_category_data_safely():
    json_path = os.path.join(settings.BASE_DIR, 'categories.json')
    
    try:
        with open(json_path, 'r') as json_file:
            try:
                return json.load(json_file)
            except json.JSONDecodeError as e:
                # 处理JSON格式错误
                print(f"Failed to parse JSON: {str(e)}")
                return None
    except FileNotFoundError:
        # 处理文件不存在的情况
        print(f"JSON file not found at: {json_path}")
        return None

4. 注意事项

  • File Placement: If you put the JSON file inside an app (e.g., myapp/data/categories.json), adjust the path to os.path.join(settings.BASE_DIR, 'myapp', 'data', 'categories.json').
  • Global Loading: If you want to load the data once when the server starts, you can put the load logic in your app's __init__.py—just make sure it runs after Django is fully initialized to avoid issues.

内容的提问来源于stack exchange,提问作者rakesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:48:01