crankshaft
crankshaft

Reputation: 2677

javascript parse string as object or JSON

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

Answers (1)

Ian
Ian

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="{&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:

Upvotes: 2

Related Questions