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"
}
]
}
I am trying to assign the above object as an attribute to an element like this:
content +='<div class="save_data" data-savereturn='+JSON.stringify(dataObj)+'></div>';
But on viewing the source it appears in the HTML like:
<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>
I further tried
console.log(JSON.stringify(dataObj));
which logs the output correct without being broken by the double quote as in the case of assigning it to the data-savereturn.
This dataObj gets created in a jQuery.each loop which is then assigned to corresponding HTML elements.
Unable to figure out the breaking of JSON which is truncating & lowercasing of the portion after the space.
It doesn't happens when the word has no space in between i.e
"Batch_Number": "PatchPA",
Update:
on start quotes double (")
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"
changed the start quotes to single (')
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
2nd one looks correct but still having JSON invalid.
content +='<div class="save_data" data-savereturn="'+JSON.stringify(dataObj)+'"></div>';<div class="save_data" data-savereturn="${JSON.stringify(dataObj).replace(/"/g, '\\"')}"></div>