代码之家  ›  专栏  ›  技术社区  ›  techie_28

当具有空格分隔的值时,json字符串在data属性内断开

  •  -1
  • techie_28  · 技术社区  · 8 年前
     var dataObj=  {
          "Cast_Code": "NA",
          "Mat_Code": "xxxx",
          "Pin_Num": "xxxx",
          "MatDetail": [
            {
              "Batch_Number": "Patch PA",
              "Batch_Expiry": "No Expiry",
              "Batch_Quantity": "xxx",
              "Return_Qty": "0.00"
            }
          ]
        }
    

    我正试图将上述对象作为属性分配给如下元素:

    content +='<div class="save_data" data-savereturn='+JSON.stringify(dataObj)+'></div>';
    

    但是在查看源代码时,它在html中显示如下:

    <div class="save_return" data-savereturn="{"Cast_Code": "NA",...,
          "MatDetail": [
            {                //Notice the double quote between "Patch PA"
              "Batch_Number": "Patch" pa","batch_expiry": "no expiry","batch_quantity": "xxx","return_qty": "0.00""
            }
          ]
        }"></div>
    

    我又试了

    console.log(JSON.stringify(dataObj));
    

    在将输出分配给 data-savereturn 是的。

    这个 数据对象 在中创建 jquery.each每个 循环,然后分配给相应的html元素。

    无法找出json的中断,该中断正在截断空格后面部分的小写字母。

    当单词之间没有空格时,即

    "Batch_Number": "PatchPA",
    

    更新:

    在 双引号(“)

    content +='<div class="save_data" data-savereturn="'+JSON.stringify(dataObj)+'"></div>';
    
    
        it shows:
    
        <div class="save_return" data-savereturn="{" Cast_Code":"na","Mat_Code":"xyz","Pin_Num":"xyz","batchdetail":[{"batch_number":"patch="" na","batch_expiry":"no="" expiry","batch_quantity":"20","return_qty":"0.00"}]}"=""></div>
    
        jQuery('.selector').data('savereturn')
         gives
        {
          "savereturn": "{"
        }
        which gives an error on JSON.parse "Uncaught SyntaxError: Unexpected end of JSON input"
    

    将开始引号改为单(')

         content +="<div class='save_data' data-savereturn='"+JSON.stringify(dataObj)+"'></div>";
    
            <div class="save_return" data-savereturn="{"Request_Code":"NA";"Mat_Code":"xx";"In_num":"xx","BatchDetail":[{"Batch_Number":"Batch NA","Batch_Expiry":"No Expiry","Batch_Quantity":"10","Return_Qty":"0.00"}]}"></div>
    
    jQuery('sel').data('savereturn') gives:
    {
      "Cast_Code": "NA",
      "Mat_Code": "tttt",
      "Tin_Number": "ppp",
      "PatchDetail": [
        {
          "Batch_Number": "Patch NA",
          "Batch_Expiry": "No Expiry",
          "Batch_Quantity": "10",
          "Return_Qty": "0.00"
        }
      ]
    }
    which also give error on JSON.parse "Uncaught SyntaxError: Unexpected token o in JSON at position 1"
    

    第二个看起来是正确的,但是json仍然无效。

    对不起,格式不好。

    1 回复  |  直到 8 年前
        1
  •  3
  •   Barmar    8 年前

    您需要在包含空格的属性以及一些其他标点字符周围加引号,因此最好 总是 引用你的特质。由于json将包含双引号,因此应该在属性周围使用单引号。

    content +="<div class='save_data' data-savereturn='"+JSON.stringify(dataObj)+"'></div>";
    

    如果您使用的是jquery,那么imo将更容易创建如下元素:

    var element = $("<div>", {
        "class": "save_data",
        data: { "savereturn": dataObj }
    });
    
    推荐文章