Farkas Imre
Farkas Imre

Reputation: 123

Given string to object convert

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

Answers (2)

KooiInc
KooiInc

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

Michael Robinson
Michael Robinson

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="{&quot;2012-03-01&quot;:1,&quot;2012-03-11&quot;:1,&quot;2012-03-21&quot;:1}"></div>

And using the following JavaScript:

var dates_allowed = $('#someif').data('dates');

scessor's example JSFiddle.

Upvotes: 1

Related Questions