简体   繁体   中英

Why is the browser changing my single quotes to double and ruining my JSON in the data attr?

This should be way easier than it is, but it's got me stuck.

Im putting some JSON in an input data attribute and the quotes on the first key are closing the attribute.

Here's what I'm trying to do:

var html = `<input type="checkbox" data-values='${dataVals}' />`;

Where dataVals is a JSON string like this

'{"checked":true,"unchecked":false}'

But it's showing up in the browser like this:

<input type="checkbox" data-values="{"checked":true,"unchecked":false}">

And the browser is reading it essentially as though it's this.

data-values="{"

Which obviously isn't what I want.

I'm clearly missing something. Any thoughts?

Combination of @TJ Crowder and @Teemu

I added a replace at the end of the json string to replace double quotes with &quot;

JSON.stringify({ ... }).replace(/\"/g, "&quot;")

Then also stopped trying to run JSON.parse() when I wanted to get the value later since $.data('values') already returns a javascript object (when it can).

JSON.parse($(this).data('values')) => $(this).data('values')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM