0

i am doing something wrong, i am passing array to html element and setting, data attribute. When i console log array got this.

enter image description here

Then doing

<img class="d-block w-100" data-title="'+JSON.stringify(value.image_tree_titles) +'" />

in html looks like this

enter image description here

But when i try JSON.Parse(), got sintax error with open bracket? Any idea what could be wrong?

Ambulance lada
  • 311
  • 1
  • 2
  • 14
  • `data-title="[{"` is what it probably thinks your attribute is. See how the coloring is all messed up? Instead of just writing `json.stringify` directly in there, you should consider encoding it (bse64, for example) OR writing it as the value of a hidden input. It might be possible to safely escape those double quotes, but I wouldn't trust it – isick Nov 22 '19 at 20:58
  • looks like it's issue with quotes – Ambulance lada Nov 22 '19 at 20:59

2 Answers2

0

The problem is the value of data-title is delimited by double quotes ("), but also contains double quotes. Any time you interpolate a string literal into a template, you need to apply encoding to the string, unless you can ensure that it's safe. In this case, because it's being embedded into HTML, you'll want to apply HTML encoding.

{"foo":"bar"} becomes {&quot;foo&quot;:&quot;bar&quot;}

See the second link for how to do this encoding in javascript. Simply replacing the double quote characters is not enough.

Sources:

Robert Stiffler
  • 675
  • 3
  • 10
-1

Here what i did

encodeURIComponent(JSON.stringify(title))

is string encoded check

function isEncoded(str) {
        return typeof str == "string" && decodeURIComponent(str) !== str;
    }

finally

JSON.parse(decodeURIComponent(title));
Ambulance lada
  • 311
  • 1
  • 2
  • 14