Skip to content

Instantly share code, notes, and snippets.

@lsauer
Created August 28, 2015 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lsauer/8044abef2a24f4dd717e to your computer and use it in GitHub Desktop.
Save lsauer/8044abef2a24f4dd717e to your computer and use it in GitHub Desktop.
JavaScript: convert css string to JSON
//converts a css string to json
var css2json = function(str){
return str
.replace(/(\w*:)/g, '$1"') //create json format
.replace(/[;]/g, '";')
.replace(/(\'{2,})/g, '"')
.replace(/;/g, ',')
.replace(/(['"])?([a-zA-Z0-9_-]+)(['"])?:/g, '"$2": ')
.replace(/,\s*\}/,'}')
.trim();
}
@SensonicsDev
Copy link

This function does not work. Here is an example:
css2json('body{font-size:12px;}p{color:red;}'); --> "body{\"font-size\": \"12px\"}p{\"color\": \"red\",}" JSON.parse(css2json('body{font-size:12px;}p{color:red;}')); --> SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data[Learn More]

@mohaimenmahi
Copy link

Thanks for sharing. It helped much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment