On Jan 5, 8:10 pm, Dave <messedupp...@gmail.com> wrote:
> Hi
>
> Wonder how I can convert a string to a json array.

>From what you've posted below, you want to process a string and treat
parts of it as JSON objects.

>
> //start code
>
> var arrCss = ["a___{'color':'red','font-weight':'bold'}", "h1,h2___
> {'color':'blue'}"];

Why not create it as a valid JSON object?

>
> for(var i = 0; i < arrCss.length; i++){
>    var snip = arrCss[i].split("___");
>    $(snip[0]).css(snip[1]);
> }
>
> //end code
>
> The problem is that .css() treats snip[1] as a string but I need it to
> handle it as a json array.

You don't want it to be a "json[sic] array", you want parts of the
string converted to an object with properties and string values, which
might be called a "JSON object". You could use:

  ...css(eval('(' + snip[1] + ')'));


A better solution might be to use a JSON object for the whole thing,
e.g.:

var xString = "{" +
        "'a':{'color':'red','font-weight':'bold'}," +
        "'h1,h2':{'color':'blue'}" +
        "}";

var xObj = eval('(' + xString + ')' );
for (var selector in xObj) {
  alert(xObj[selector].color); // red, blue
}

Which might be used in your posted code as:

var xObj = eval('(' + xString + ')' );
for (var selector in xObj) {
  $(selector).css(xObj[selector]);
}


> Bad: .css("{'color':'red','font-weight':'bold'}");
> Good: .css({'color':'red','font-weight':'bold'});


--
Rob

Reply via email to