Reputation: 2677
I want to be able to define a hash pair inside an html element as an attribute and then parse it into an object to be processed by javascript.
example:
<div id="test" mydata="{'xkey':'xval','ykey':'yval'}">
<script>
var mydata = JSON.parse($('#test').attr('mydata'));
console.log(mydata.xkey);
</script>
But the problem is it is not being converted into an object and the output is undefined.
How can I achieve this ??
Upvotes: 1
Views: 131
Reputation: 50905
Use double quotes instead, to surround keys and string values:
mydata='{"xkey":"xval","ykey":"yval"}'
DEMO: http://jsfiddle.net/reAtQ/
If you must keep the surround double quotes, you can encode the inner ones:
mydata="{"xkey":"xval","ykey":"yval"}"
DEMO: http://jsfiddle.net/reAtQ/1/
Or, you could replace
all single quotes with double quotes before parsing:
var mydata = JSON.parse($('#test').attr('mydata').replace(/'/g, '"'));
DEMO: http://jsfiddle.net/reAtQ/2/
Although note that if any of the keys/values contain a single quotes, they will be inadvertently replaced.
Reference:
Upvotes: 2