Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS to JSON Parser or Converter

I'm working on a non-web platform with no HTML or CSS layer, just a pure JavaScript implementation.

I would like to load a CSS file as a text string using AJAX, parse the CSS into a JS objects or JSON, and then use utility library to interpret what styles should be applied to an element in the DOM tree.

How would I do that?

like image 731
jonycheung Avatar asked Mar 09 '11 02:03

jonycheung


People also ask

Can you use CSS in JSON?

Custom selector property/values can be used in CSS JSON as a mechanism to extend CSS. CSS text pre-processing is possible through the mapping of a specfied property to a conditionally executed parsing routine.

Why do we use JSON parser?

JSON.parse() A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with JSON.parse() , and the data becomes a JavaScript object.

Does JSON parse automatically?

The JSON file will be parsed for you automatically and you can start using it in your project: const jokes = require('./jokes. json'); console.

What does JSON parse () method do?

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.


2 Answers

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

like image 74
laher Avatar answered Oct 09 '22 21:10

laher


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);
like image 41
Aram Kocharyan Avatar answered Oct 09 '22 23:10

Aram Kocharyan