【问题标题】:converting a JSON string back to an array将 JSON 字符串转换回数组
【发布时间】:2015-11-06 06:41:24
【问题描述】:

我通过 ajax 将浮点值的二维数组传递给我的 views.py。我的 ajax 调用如下所示:

$.ajax({
          method: "POST",
          url: "introURL",
          data: {
            csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
            dsg_mtx : JSON.stringify(dsg_mtx),

           },
          success: function(data) {

            document.getElementById("test").innerHTML = data;  // echo response
          },
          error: function() {
            alert ("Something went wrong");
          }

我通过这个调用将我的数据拉到视图中:

def introURL(request):
    if request.is_ajax():
        try:
            designMtx = json.loads(request.POST['dsg_mtx'], parse_float=None)

        except KeyError:
            return HttpResponse('Error, intro import') 

        ... Some transformation of designMtx...


        return HttpResponse(response)       
    else:
        raise Http404   

所以我的问题是如何将此 json 字符串化对象转换回可用于计算响应的二维数组?如您所见,我尝试使用 parse_float 选项,但它仍然是 str 数据类型。

传递的数组 dsg_mtx 是使用 Handson 表创建的,如下所示:

-1  -1
-1  1
1   -1
1   1

感谢您的指导。

【问题讨论】:

  • 请出示dsg_mtx
  • 在我上面的代码中添加了 dsg_mtx 的图形表示。
  • $.ajax 之前添加console.log(dsg_mtx) 并显示控制台中的内容。在json.loads之前的Python代码中以同样的方式添加print request.POST['dsg_mtx']并显示输出中的内容。
  • 我想我看到了这个问题......我的 Handson 表是作为二维数字数组启动的,但是只要我在单元格中键入任何内容,它就会将该单元格中的值转换为字符串。所以我得看看为什么 Handson 表会这样。

标签: python arrays json ajax


【解决方案1】:

我的问题原来是handsontable的默认设置。当我为表格提供浮点值时,默认情况下,表格将它们转换为字符串。所以我发布了一个看起来像浮点数的字符串矩阵。解决方法是重新格式化放置数据的可手动操作的单元格。

var data = function () {
   return Handsontable.helper.createSpreadsheetData(mtxrows, mtxcols);
  };

  var hot = new Handsontable(container, {
    data: data,
    height: 480,
    colHeaders: true,
    rowHeaders: true,
    stretchH: 'none',
    columnSorting: true,
    contextMenu: true,
    className: "htCenter",
    cells: function (row, col, prop) {
        var cellProperties = {};
        if (row > 0) {
          cellProperties.type = 'numeric';
          cellProperties.format = '0[.]000';
         }                      
        return cellProperties;
        },

    afterChange: function () {
        var tmpData = JSON.parse(JSON.stringify(mtx_data));
    }
  });

所以基本上第一行之后的任何东西都设置为数字类型。

所以现在我的 ajax 调用中的这一行:

dsg_mtx : JSON.stringify(dsg_mtx),

正确格式化它,views.py 使用这个调用来正确加载它:

designMtx = json.loads(request.POST['dsg_mtx'])

感谢 Tomasz Jakub 建议 console.log() 帮助我诊断问题。

问候, 詹姆

【讨论】:

    【解决方案2】:

    尝试json.loads,但在parse_float 中通过decimal.Decimal

    designMtx = json.loads(request.POST['dsg_mtx'], parse_float=decimal.Decimal)
    

    【讨论】:

    • 试过了,但它说十进制没有定义。添加后: from decimal import Decimal 并将代码更改为: ... parse_float=Decimal 代码运行,但对结果没有影响。 designMtx 仍然只是一个字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多