1

我正在尝试将 jqGrid 导出为 CSV。到目前为止,我在 jqGrid 的标题中添加了一个按钮,该按钮运行一个指向 CSV 下载 url 的 javascript 函数,该函数具有一个包含变量的 get 请求:1)JSON 所在的 url 和 2)来自 jqGrid 的 urlencoded 标头。

我确实喜欢这样(“网格”是要下载的网格的名称):

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,但出现错误:

JSONDecodeError at /csv/download/

No JSON object could be decoded: line 1 column 0 (char 0)

我正在使用 python 2.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"}
4

1 回答 1

1

这是一个更好的方法。无需打开与 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
于 2012-12-16T15:27:23.900 回答