使用Django和Python创建JSON响应

Swi*_*tch 433 python django json

我正在尝试将服务器端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.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是转换后的代码

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))
Run Code Online (Sandbox Code Playgroud)

我正在使用simplejson来编码Python列表(因此它将返回一个JSON数组).我还无法弄清楚问题.但我认为我对'回声'做错了.

Tom*_*Tom 886

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

import json

from django.http import HttpResponse

response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'
Run Code Online (Sandbox Code Playgroud)

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

return HttpResponse(json.dumps(response_data), content_type="application/json")
Run Code Online (Sandbox Code Playgroud)

对于Django 1.7+,使用如此SO答案JsonResponse所示:

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
Run Code Online (Sandbox Code Playgroud)

  • 抱歉,我写的不清楚,但我只是想使用字典,因为在将其序列化为JSON时它更干净/更容易. (5认同)
  • 它*是mimetype,而不是应该让他遇到麻烦的列表.虽然大多数JSON通常是顶层的对象("词典"),但JSON对顶层的数组非常满意. (4认同)

srj*_*srj 156

django 1.7的新功能

你可以使用JsonResponse对象.

来自文档:

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
Run Code Online (Sandbox Code Playgroud)

  • 一个缺点:它默认为`ensure_ascii`,我还没有找到覆盖它的方法.为此创建了一个新问题:http://stackoverflow.com/q/34798703/854477 (2认同)

Din*_*ngo 138

我用它,它工作正常.

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')
Run Code Online (Sandbox Code Playgroud)

替代方案:

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,
        )
Run Code Online (Sandbox Code Playgroud)

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

from django.http import JsonResponse
def some_view(request):
    return JsonResponse({"key": "value"})
Run Code Online (Sandbox Code Playgroud)

  • 使用python 2.7,它应该只是"import json" (2认同)

Akh*_*rus 24

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

from django.http import JsonResponse
...
return JsonResponse(array_to_js, safe=False)
Run Code Online (Sandbox Code Playgroud)

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


Dmi*_*nko 16

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)
Run Code Online (Sandbox Code Playgroud)

在视图中:

resp_data = {'my_key': 'my value',}
return JsonResponse(resp_data)
Run Code Online (Sandbox Code Playgroud)


And*_*res 15

对于那些使用Django 1.7+的人

from django.http import JsonResponse

def your_view(request):
    json_object = {'key': "value"}
    return JsonResponse(json_object)
Run Code Online (Sandbox Code Playgroud)

官方文件


Red*_*xDJ 11

您将要使用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")
Run Code Online (Sandbox Code Playgroud)

  • 这是我的首选版本,但意识到它[只吃Django QuerySets](http://stackoverflow.com/questions/9061068/django-json-dict-object-has-no-attribute-meta). (2认同)

eli*_*lim 8

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

from django.views import View
from django.http import JsonResponse

class JsonView(View):
    def get(self, request):
        return JsonResponse({'some': 'data'})
Run Code Online (Sandbox Code Playgroud)

使用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'})
Run Code Online (Sandbox Code Playgroud)


小智 6

如何使用ajax(json)的谷歌应用引擎?

使用JQuery编写Javascript代码:

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

代码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)
Run Code Online (Sandbox Code Playgroud)


Tan*_*y D 6

它与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)
Run Code Online (Sandbox Code Playgroud)

对于旧版本的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')
Run Code Online (Sandbox Code Playgroud)


dro*_*oon 5

这是我使用基于类的视图的首选版本。只需对基本 View 进行子类化并重写 get() 方法即可。

import json

class MyJsonView(View):

    def get(self, *args, **kwargs):
        resp = {'my_key': 'my value',}
        return HttpResponse(json.dumps(resp), mimetype="application/json" )
Run Code Online (Sandbox Code Playgroud)


Raj*_*nka 5

Django 代码views.py

def view(request):
    if request.method == 'POST':
        print request.body
        data = request.body
        return HttpResponse(json.dumps(data))
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)


小智 5

首先导入这个:

from django.http import HttpResponse
Run Code Online (Sandbox Code Playgroud)

如果您已经有了 JSON:

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

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

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