Reputation: 123
I have to current string taken from
<div id="someif" array-data="2012-03-01:1,2012-03-11:1,2012-03-21:1"></div>
var mystring={2012-03-01:1,2012-03-11:1,2012-03-21:1}
and need this js object created
var dates_allowed = {
'2012-03-01': 1,
'2012-03-11': 1,
'2012-03-21': 13
};
i have tried with but no result - i get error
jQuery.parseJSON(myString);
Thanks!
Upvotes: 0
Views: 116
Reputation: 122906
You can't parse a string like '2012-03-01:1,2012-03-11:1,2012-03-21:1' with JSON
This string would be parseable:
'[{"allowed":"2012-03-01","index":"1"}, {"allowed":"2012-03-11","index":"1"},{"allowed":"2012-03-21","index":"1"}]'
So, used as data attribute
<div id="someif" data-allowed='[{"allowed":"2012-03-01","index":"1"}, {"allowed":"2012-03-11","index":"1"},{"allowed":"2012-03-21","index":"1"}]'>
var myAllowedDates = JSON.parse($('#someif').attr('data-allowed'));
See this jsfiddle
Upvotes: 0
Reputation: 29498
Solution
Working with your current HTML, you could do something like this:
var dates_allowed = {};
$('#someif').attr('array-data').split(',').each(function(){
var date = this.split(',');
dates_allowed[date[0]] = date[1];
});
Better solution
But in my opinion you'd be better off leveraging jQuery data by changing your HTML to something like:
<div id="someif" data-dates="{"2012-03-01":1,"2012-03-11":1,"2012-03-21":1}"></div>
And using the following JavaScript:
var dates_allowed = $('#someif').data('dates');
Upvotes: 1