我正在尝试将jqGrid导出为CSV。到目前为止,我在jqGrid的标题中添加了一个按钮,该按钮运行一个javascript函数,指向带有变量的get请求的CSV下载URL:1)JSON所在的url和2)来自jqGrid的urlencoded标头。
我确实喜欢这个('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,但是我收到错误:
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"}
答案 0 :(得分: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