当具有空格分隔值时,JSON字符串化字符串在数据属性内断开

6tqwzwtp  于 2023-02-26  发布在  其他
关注(0)|答案(1)|浏览(148)
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的情况那样被双引号打断。

    • dataObjjQuery.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

未捕获的语法错误:JSON中位置1处的意外标记o
第二个看起来正确,但JSON仍然无效。

kxe2p93d

kxe2p93d1#

您需要在包含空格和其他标点符号的属性周围加上引号,因此最好 * 总是 * 将属性括起来。由于JSON将包含双引号,因此您应该在属性周围使用单引号。

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

如果您使用jQuery,那么像这样创建元素会更容易:

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

相关问题