Python处理JSON解码错误,导出jqGrid

2024-04-19 00:25:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将jqGrid导出到CSV。到目前为止,我在jqGrid的标题中添加了一个按钮,该按钮运行一个javascript函数,该函数指向一个CSV dowload url,其中包含一个变量:1)JSON所在的url;2)来自jqGrid的url编码头。在

我是这样做的(“grid”是要下载的网格的名称):

function downloadGrid(grid) {  
    var columnNames = $(grid).getGridParam("colNames");
    columnNames = encodeURIComponent(columnNames)
    var dataLoc = $(grid).getGridParam("url");
    window.open( "/csv/download/?header=" + columnNames+"&jqgrid=" + dataLoc);
    } 

在编写CSV文件的视图中,我试图使用simplejson读取一些json,但是我得到了错误:

^{pr2}$

我使用的是python2.7.1和simplejson 2.6.2,对simplejson的回溯到第426行。在

视图如下:

import simplejson as json
import csv
import urllib2
from django.http import HttpResponse
from settings import PRIMARY_DOMAIN

def csv_writer(request):
    response = HttpResponse(mimetype='text/csv')
    dat = '%s' % datetime.now()
    dat = dat[0:16]
    response['Content-Disposition'] = 'attachment; filename="CSV_%s.csv"' % dat

    writer = csv.writer(response)
    json_data = urllib2.urlopen(PRIMARY_DOMAIN + '/json/test_day/4982/')

    if request.method == "GET":
        if 'header' in request.GET.keys():
            header = request.GET['header'].split(',')
            writer.writerow([str(x) for x in header])
        if 'jqgrid' in request.GET.keys():
            url = request.GET['jqgrid']
            json_data = urllib2.urlopen(PRIMARY_DOMAIN + url)

    data = json.loads(json_data.read())

    ###below here may not work, haven't gotten past the json.loads()
    for row in data:
        writer.writerow(row)

    return response

这里有两个json失败的例子:

{"records": "0", "total": "1", "rows": [], "page": "1"}

另一个是:

{"records": "17", "total": "1", "rows": [{"cell": ["04/05/10", 4, 196, 73, 3.0, 3.6, 1.5, 0.83, 8.0, 67, 28452, "", 115, 3.2, "$20.76", "$15.16"], "id": 1}, {"cell": ["01/30/10", 4, 131, 75, 4.0, 3.0, null, 1.33, null, 81, null, "", 141, 3.5, "$18.34", "$13.75"], "id": 2}, {"cell": ["01/06/10", 4, 107, 114, 3.3, 3.0, null, 1.1, null, 110, null, "", 283, 4.5, "$17.11", "$19.50"], "id": 3}, {"cell": ["11/28/09", 4, 68, 105, 3.7, 2.8, null, 1.32, null, 108, null, "", 214, 4.1, "$17.30", "$18.16"], "id": 4}, {"cell": ["11/02/09", 4, 42, 99, 4.1, 2.5, null, 1.64, null, 108, null, "", 47, 1.9, "$17.40", "$17.23"], "id": 5}, {"cell": ["10/02/09", 4, 11, 94, 3.9, 3.2, null, 1.22, null, 100, null, "", 17, 0.4, "$19.29", "$18.13"], "id": 6}], "page": "1"}

Tags: csvimportidjsonurldatagetrequest
1条回答
网友
1楼 · 发布于 2024-04-19 00:25:05

这里有一个更好的方法。不需要打开与urllib2的新连接,您需要的一切都在django中。在

from django.core.urlresolvers import resolve
view_match = resolve('/json/test_day/4982/')
json_data = view_match.func(request,**view_match.kwargs).content

相关问题 更多 >