Created
August 28, 2015 08:58
-
-
Save lsauer/8044abef2a24f4dd717e to your computer and use it in GitHub Desktop.
JavaScript: convert css string to JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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(); | |
} |
Thanks for sharing. It helped much.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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]