【问题标题】:Creating a JSON response using Django and Python使用 Django 和 Python 创建 JSON 响应
【发布时间】:2011-01-26 13:14:37
【问题描述】:

我正在尝试将服务器端 Ajax 响应脚本转换为 Django HttpResponse,但显然它不起作用。

这是服务器端脚本:

/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];

/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
$arrayToJs[1] = $validateError;

if($validateValue =="Testuser"){  // Validate??
    $arrayToJs[2] = "true";       // RETURN TRUE
    echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';  // RETURN ARRAY WITH success
}
else{
    for($x=0;$x<1000000;$x++){
        if($x == 990000){
            $arrayToJs[2] = "false";
            echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';   // RETURNS ARRAY WITH ERROR.
        }
    }
}

这是转换后的代码

def validate_user(request):
    if request.method == 'POST':
        vld_value = request.POST.get('validateValue')
        vld_id = request.POST.get('validateId')
        vld_error = request.POST.get('validateError')

        array_to_js = [vld_id, vld_error, False]

        if vld_value == "TestUser":
            array_to_js[2] = True
            x = simplejson.dumps(array_to_js)
            return HttpResponse(x)
        else:
            array_to_js[2] = False
            x = simplejson.dumps(array_to_js)
            error = 'Error'
            return render_to_response('index.html',{'error':error},context_instance=RequestContext(request))
    return render_to_response('index.html',context_instance=RequestContext(request))

我正在使用 simplejson 对 Python 列表进行编码(因此它将返回一个 JSON 数组)。我还没有弄清楚问题所在。但我认为我对“回声”做错了。

【问题讨论】:

  • 你也可以使用 django-annoying view decorator @ajax_request.

标签: python django json


【解决方案1】:

我通常使用字典而不是列表来返回 JSON 内容。

import json

from django.http import HttpResponse

response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'

Pre-Django 1.7 你会这样返回它:

return HttpResponse(json.dumps(response_data), content_type="application/json")

对于 Django 1.7+,使用JsonResponse,如this SO answer 所示:

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

【讨论】:

  • mimetype,而不是应该给他带来麻烦的列表。虽然大多数 JSON 通常是顶层的对象(“字典”),但 JSON 对顶层的数组非常满意。
  • 抱歉,我写的内容不清楚,但我只是说我使用字典,因为它在序列化为 JSON 时更干净/更容易。
  • 'application/json' 在旧版本的 IE 中不被正确支持。以下是对问题的一些讨论github.com/blueimp/jQuery-File-Upload/issues/123
【解决方案2】:

django 1.7 中的新功能

您可以使用JsonResponse 对象。

来自文档:

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

【讨论】:

  • 一个缺点:它默认为ensure_ascii,我还没有找到覆盖它的方法。为此创建了一个新问题:stackoverflow.com/q/34798703/854477
  • @int_ua: 只需添加json_dumps_params={"ensure_ascii": False}(需要 Django 1.9 或更高版本)
【解决方案3】:

我用这个,效果很好。

from django.utils import simplejson
from django.http import HttpResponse

def some_view(request):
    to_json = {
        "key1": "value1",
        "key2": "value2"
    }
    return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')

替代方案:

from django.utils import simplejson

class JsonResponse(HttpResponse):
    """
        JSON response
    """
    def __init__(self, content, mimetype='application/json', status=None, content_type=None):
        super(JsonResponse, self).__init__(
            content=simplejson.dumps(content),
            mimetype=mimetype,
            status=status,
            content_type=content_type,
        )

在 Django 1.7 中,JsonResponse 对象已添加到 Django 框架本身,这使得这项任务更加容易:

from django.http import JsonResponse
def some_view(request):
    return JsonResponse({"key": "value"})

【讨论】:

  • 问题在于它没有从输入字段中获取值 vld_value = request.POST.get('validateValue')
  • 使用python 2.7,它应该只是“import json”
  • 我认为from django.utils import simplejson 是为了向后兼容。
  • JsonResponse(status=404, data={'status':'false','message':message})
【解决方案4】:

从 Django 1.7 开始,您就有了一个标准的 JsonResponse,这正是您所需要的:

from django.http import JsonResponse
...
return JsonResponse(array_to_js, safe=False)

你甚至不需要 json.dump 你的数组。

【讨论】:

    【解决方案5】:

    对于那些使用 Django 1.7+ 的人

    from django.http import JsonResponse
    
    def your_view(request):
        json_object = {'key': "value"}
        return JsonResponse(json_object)
    

    official docs

    【讨论】:

      【解决方案6】:
      from django.http import HttpResponse
      import json
      
      class JsonResponse(HttpResponse):
          def __init__(self, content={}, mimetype=None, status=None,
                   content_type='application/json'):
              super(JsonResponse, self).__init__(json.dumps(content), mimetype=mimetype,
                                                 status=status, content_type=content_type)
      

      在视图中:

      resp_data = {'my_key': 'my value',}
      return JsonResponse(resp_data)
      

      【讨论】:

        【解决方案7】:

        使用基于 Django 类的视图,您可以编写:

        from django.views import View
        from django.http import JsonResponse
        
        class JsonView(View):
            def get(self, request):
                return JsonResponse({'some': 'data'})
        

        使用 Django-Rest-Framework,您可以编写:

        from rest_framework.views import APIView
        from rest_framework.response import Response
        
        class JsonView(APIView):
            def get(self, request):
                return Response({'some': 'data'})
        

        【讨论】:

          【解决方案8】:

          您需要使用 django 序列化程序来帮助处理 unicode 内容:

          from django.core import serializers
          
          json_serializer = serializers.get_serializer("json")()
              response =  json_serializer.serialize(list, ensure_ascii=False, indent=2, use_natural_keys=True)
              return HttpResponse(response, mimetype="application/json")
          

          【讨论】:

          【解决方案9】:

          使用 Django 1.7 或更高版本非常方便,因为您有 JsonResponse 类,它是 HttpResponse 的子类。

          from django.http import JsonResponse
              def profile(request):
                  data = {
                      'name': 'Raghav',
                      'location': 'India',
                      'is_active': False,
                      'count': 28
                  }
                  return JsonResponse(data)
          

          对于旧版本的 Django,您必须使用 HttpResponse 对象。

          import json
          from django.http import HttpResponse
          
          def profile(request):
              data = {
                  'name': 'Raghav',
                  'location': 'India',
                  'is_active': False,
                  'count': 28
              }
              dump = json.dumps(data)
              return HttpResponse(dump, content_type='application/json')
          

          【讨论】:

            【解决方案10】:

            How to use google app engine with ajax (json)?

            用 JQuery 编写 Javascript:

            $.ajax({
                url: '/ajax',
                dataType : 'json',
                cache: false,
                success: function(data) {
                    alert('Load was performed.'+data.ajax_resp);
                }
            });
            

            代码 Python

            class Ajax(webapp2.RequestHandler):
                def get(self):
                    my_response = {'ajax_resp':'Hello, webapp World!'}
                    datos = json.dumps(my_response)
            
                    self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
                    self.response.out.write(datos)
            

            【讨论】:

              【解决方案11】:

              Django 代码views.py

              def view(request):
                  if request.method == 'POST':
                      print request.body
                      data = request.body
                      return HttpResponse(json.dumps(data))
              

              HTML 代码view.html:

              <!DOCTYPE html>
              <html>
              <head>
              <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
              <script>
              $(document).ready(function(){
                  $("#mySelect").change(function(){
                      selected = $("#mySelect option:selected").text()
                      $.ajax({
                          type: 'POST',
                          dataType: 'json',
                          contentType: 'application/json; charset=utf-8',
                          url: '/view/',
                          data: {
                                  'fruit': selected
                                },
                          success: function(result) {
                                      document.write(result)
                                  }
                  });
                });
              });
              </script>
              </head>
              <body>
              
              <form>
                  {{data}}
                  <br>
              Select your favorite fruit:
              <select id="mySelect">
                <option value="apple" selected >Select fruit</option>
                <option value="apple">Apple</option>
                <option value="orange">Orange</option>
                <option value="pineapple">Pineapple</option>
                <option value="banana">Banana</option>
              </select>
              </form>
              </body>
              </html>
              

              【讨论】:

                【解决方案12】:

                首先导入这个:

                from django.http import HttpResponse
                

                如果您已经拥有 JSON:

                def your_method(request):
                    your_json = [{'key1': value, 'key2': value}]
                    return HttpResponse(your_json, 'application/json')
                

                如果您从另一个 HTTP 请求中获取 JSON:

                def your_method(request):
                    response = request.get('https://www.example.com/get/json')
                    return HttpResponse(response, 'application/json')
                

                【讨论】:

                  【解决方案13】:

                  这是我使用基于类的视图的首选版本。 只需子类化基本视图并覆盖 get() 方法。

                  import json
                  
                  class MyJsonView(View):
                  
                      def get(self, *args, **kwargs):
                          resp = {'my_key': 'my value',}
                          return HttpResponse(json.dumps(resp), mimetype="application/json" )
                  

                  【讨论】:

                    【解决方案14】:

                    使用 JsonResponse

                    from django.http import JsonResponse
                    

                    【讨论】:

                    • 这个答案需要上下文和解释。
                    【解决方案15】:

                    在视图中使用这个:

                    form.field.errors|striptags
                    

                    用于在没有 html 的情况下获取验证消息

                    【讨论】:

                      【解决方案16】:

                      这些答案中的大多数都已过时。不建议使用 JsonResponse,因为它会转义字符,这通常是不受欢迎的。这是我使用的:

                      views.py(返回 HTML)

                      from django.shortcuts import render
                      from django.core import serializers
                      
                      def your_view(request):
                          data = serializers.serialize('json', YourModel.objects.all())
                          context = {"data":data}
                          return render(request, "your_view.html", context)
                      

                      views.py(返回 JSON)

                      from django.core import serializers
                      from django.http import HttpResponse
                      
                      def your_view(request):
                          data = serializers.serialize('json', YourModel.objects.all())
                          return HttpResponse(data, content_type='application/json')
                      

                      Vue 用户奖励

                      如果你想将你的 Django Queryset 引入 Vue,你可以执行以下操作。

                      template.html

                      <div id="dataJson" style="display:none">
                      {{ data }}
                      </div>
                      
                      <script>
                      let dataParsed = JSON.parse(document.getElementById('dataJson').textContent);
                      var app = new Vue({
                        el: '#app',
                        data: {
                          yourVariable: dataParsed,
                        },
                      })
                      </script>
                      

                      【讨论】:

                        【解决方案17】:
                        def your_view(request):
                            response = {'key': "value"}
                            return JsonResponse(json.dumps(response), content_type="application/json",safe=False)
                        

                        #指定content_type,使用json.dump()子作为不作为对象发送的内容

                        【讨论】:

                        • 如果你调用 django.http.JsonResponse() 你不必转储内容并且默认的 content_type 已经设置为 application/json
                        【解决方案18】:
                        >>> from django.http import JsonResponse
                        >>> response = JsonResponse({'foo': 'bar'})
                        >>> response.content
                        b'{"foo": "bar"}'
                        

                        Know more

                        【讨论】:

                          猜你喜欢
                          • 2012-09-15
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 2012-02-13
                          • 1970-01-01
                          • 2011-06-18
                          相关资源
                          最近更新 更多