CSS to JSON Parser or Converter

I think you're looking for a "JavaScript CSS parser".

Have you looked at either of these?

http://www.glazman.org/JSCSSP/

or

http://bililite.com/blog/2009/01/16/jquery-css-parser/

The first one looks like a good fit, but if you like jQuery then maybe you'd prefer the second one.

HTH


Try the below code "without" any external library:

function cssToJson(cssStr){
var tmp="";
//handling the colon in psuedo-classes
var openBraces=0;
for(var i=0;i<cssStr.length;i++){
    var c=cssStr[i];
    if(c=="{"){openBraces++;}
    else if(c=="}"){openBraces--;}
    if(openBraces==0 && c==":"){
        tmp+="_--_";
    } else {
        tmp+=c;
    }
}
cssStr=tmp;
cssStr=cssStr.split("\"").join("'");
cssStr=cssStr.split(" ").join("_SPACE_");
cssStr=cssStr.split("\r").join("");
cssStr=cssStr.split("\n").join("");
cssStr=cssStr.split("\t").join("");
cssStr=cssStr.split("}").join("\"}####\"");
cssStr=cssStr.split(";\"").join("\"");
cssStr=cssStr.split(":").join("\":\"");
cssStr=cssStr.split("{").join("\":{\"");
cssStr=cssStr.split(";").join("\",\"");
cssStr=cssStr.split("####").join(",");
cssStr=cssStr.split("_--_").join(":");
cssStr=cssStr.split("_SPACE_").join(" ");
if(cssStr.endsWith(",")){
    cssStr=cssStr.substr(0,cssStr.length-1);
}
if(cssStr.endsWith(",\"")){
    cssStr=cssStr.substr(0,cssStr.length-2);
}
cssStr="{\""+cssStr+"}";
try{
    var jsn=JSON.parse(cssStr);
    return jsn;
} catch(e){
    console.log(e);
    return null;
}
}

I looked at both the links @amir75 suggested. The first looked best, but the code was far too long for what I was doing. I decided to put a lightweight script together. It doesn't use jQuery, but you can if you want to load a CSS file using .get() etc. Take a look at the example.html and the js console output to get a look at the structure. You can choose to keep the order of the elements if you're using comments in the CSS, or otherwise it will still keep the order of the elements but not those of the comments while using a simpler JSON structure.

https://github.com/aramkocharyan/CSSJSON

Usage:

// To JSON, ignoring order of comments etc
var json = CSSJSON.toJSON(cssString);

// To JSON, keeping order of comments etc
var json = CSSJSON.toJSON(cssString, true);

// To CSS
var css = CSSJSON.toCSS(jsonObject);