1

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 ??

crankshaft
  • 2,607
  • 4
  • 45
  • 77

1 Answers1

2

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="{&quot;xkey&quot;:&quot;xval&quot;,&quot;ykey&quot;:&quot;yval&quot;}"

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:

Community
  • 1
  • 1
Ian
  • 50,146
  • 13
  • 101
  • 111
  • Thanks, but is using single quotes to define html element attributes acceptable ?? - If so, this will probably be the only attribute that is defined with single rather than double quotes. – crankshaft May 17 '13 at 04:27
  • @crankshaft Of course! You can mix and match single and double quotes in HTML (and JavaScript), as long as it is done so properly, but the JSON specification says that strings (which keys are) must be surrounded by double quotes. You could always change my example to use surrounding double quotes, but escape every inner double quote - it's just unnecessary to do all that escaping when you can avoid it by wrapping it with single quotes – Ian May 17 '13 at 04:30
  • Problem is, the person who will be maintaining the HTML is not me, and as this is likely to be the only exception, I would really like to keep the attribute quotes as double quotes to avoid errors / confusion, so I guess the only way would be a global replace of single with double quotes ? – crankshaft May 17 '13 at 04:38
  • @crankshaft Alrighty, well I updated my answer for what you could use :) – Ian May 17 '13 at 04:43
  • Thanks so much, I am going with the global replace. – crankshaft May 17 '13 at 05:07