4
 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.

8
  • 4
    You need to escape the quotes Commented Jul 13, 2018 at 19:18
  • 1
    content +='<div class="save_data" data-savereturn="'+JSON.stringify(dataObj)+'"></div>'; Commented Jul 13, 2018 at 19:19
  • 1
    @Callam that would be even worse. Swap the quotes. Commented Jul 13, 2018 at 19:24
  • <div class="save_data" data-savereturn="${JSON.stringify(dataObj).replace(/"/g, '\\"')}"></div> Commented Jul 13, 2018 at 19:30
  • 1
    For me this worked better JSON.stringify(dataObj).replace(/"/g, '&quot;') Commented Jun 18, 2019 at 15:15

2 Answers 2

5

You need to put quotes around an attribute that contains spaces, as well as some other punctuation characters, so it's best to always quote your attributes. Since the JSON will contain double quotes, you should use single quotes around the attribute.

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

Note that this won't work properly if there are any single quotes in dataObj; they won't be encoded to prevent from terminating the data-savereturn attribute.

If you're using jQuery, it would be easier IMO to create the element like this:

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

and this also solves that problem. In plain JavaScript this would be:

let element = document.createElement("div");
element.classList.add("save_data");
element.datalist.savereturn = JSON.stringify(dataObj);
Sign up to request clarification or add additional context in comments.

12 Comments

would this approach concatenate on an already running string variable like content +=?
If you use this approach you would generally use .append() to add the element to a DIV, rather than dealing with HTML strings.
Actually content contains whole html of page appended into it over several loops and conditions and this is needed to be attached along.This is then assigned to a central div by using .html() method of jQuery.Dont know if it is the right approach but it is an ongoing thing so little chance to change that.
Then use the first part of the answer.
There are pros and cons. Constructing the HTML string and inserting it into the DOM at the end is fast. But you can run into problems if you're not careful about the syntax. When you're inserting complex data like JSON, the latter could be an issue.
|
-2

This topic is too old, but I think others like me would come across the same issue while stringify some object that contains a value whith spaces.

A possible approach to deal this problem is to replace the value with space by ' ', a "non-breaking space" special char code like this:

var Batch_Number = value_from_somewhere.replace(" ", ' ');

2 Comments

That's a really bad idea. It messes with the data in absolutely unexpected ways.
no such thing as non breaking space... just empty space.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.