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

从JSON编码数据生成自定义CSV导出方案咨询

Export JSON Field Data as CSV from Django ModelAdmin

Here's a practical, step-by-step approach to extract JSON data from a specific field in your ModelAdmin and export it as a structured CSV:

1. Create a Custom Admin Action

Instead of relying on default export tools, build a custom admin action to take full control of parsing the JSON and formatting the output. This lets you tailor the process exactly to your data structure.

from django.contrib import admin
from django.http import HttpResponse
import json
import csv
from io import StringIO
from .models import YourModel  # Replace with your actual model

class YourModelAdmin(admin.ModelAdmin):
    list_display = ('id', 'json_field', 'other_field')  # Your existing list columns
    actions = ['export_json_field_to_csv']  # Register the custom action

    def export_json_field_to_csv(self, request, queryset):
        # Initialize variables to collect CSV data
        csv_rows = []
        all_headers = set()

        # Loop through selected objects to parse JSON
        for obj in queryset:
            try:
                # Parse the JSON field (update 'json_field' to your actual field name)
                parsed_json = json.loads(obj.json_field)

                # Handle common case: JSON is a list of objects
                if isinstance(parsed_json, list):
                    for item in parsed_json:
                        # Collect all unique keys to use as CSV headers
                        all_headers.update(item.keys())
                        csv_rows.append(item)
                # Handle case: JSON is a single object
                elif isinstance(parsed_json, dict):
                    all_headers.update(parsed_json.keys())
                    csv_rows.append(parsed_json)
                else:
                    # Skip invalid JSON structures and notify
                    self.message_user(request, f"Skipping object {obj.id}: JSON is not an object/list", level=admin.WARNING)
            except json.JSONDecodeError:
                # Catch malformed JSON and warn
                self.message_user(request, f"Invalid JSON in object {obj.id}", level=admin.WARNING)
                continue

        # Exit early if no valid data was found
        if not csv_rows:
            self.message_user(request, "No valid JSON data to export", level=admin.WARNING)
            return

        # Sort headers for consistent CSV output
        sorted_headers = sorted(all_headers)

        # Generate CSV content
        buffer = StringIO()
        writer = csv.DictWriter(buffer, fieldnames=sorted_headers)
        writer.writeheader()
        writer.writerows(csv_rows)

        # Prepare downloadable response
        response = HttpResponse(buffer.getvalue(), content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="json_data_export.csv"'
        return response

    # Set a user-friendly name for the action in the admin
    export_json_field_to_csv.short_description = "Export JSON field data to CSV"

admin.site.register(YourModel, YourModelAdmin)

2. Key Considerations

  • Nested JSON Handling: If your JSON has nested structures (e.g., {"user": {"name": "Alice", "age": 30}}), add a helper function to flatten these into flat headers like user_name and user_age.
  • Data Consistency: If different JSON entries have varying fields, the CSV will include all unique headers, with empty values for missing fields in specific rows.
  • Selection Control: The action works with both selected rows (choose specific objects in the admin) and all objects (select none to export everything).
  • Error Resilience: The try-except blocks ensure invalid JSON doesn't break the entire export, and you get clear warnings about problematic objects.

3. Alternative: Using Django Import-Export (Optional)

If you already use the Django Import-Export library, you can extend it by creating a custom resource class. Override the export method to parse the JSON field and generate CSV rows, but the custom admin action above is more lightweight for this specific use case.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:57:34