Convert an HTML Style attribute string to a JSON Object for React

I had an SVG I wanted to place in my Javascript as a React Component

To do this I was required to convert the Style string to a Javascript JSON Object.

This is my solution. Simply add this to your .zshrc file and you at the command line you can run the function and convert from a Node shell.

function htmlStyleStringToReactJSObject() {
node -e '
var ctx = require("repl").start("$ ").context;

ctx.util = require("util");

ctx.snakeCaseToCamelCase = str => {
  return str.split("-").reduce((acc, cur, i) => { return i === 0 ? acc += cur : acc += cur[0].toUpperCase() + cur.slice(1); }, "");

ctx.styleStringToJSON = str => {
  return str.split(";").map(p => p.split(":")).filter(p => p.length == 2).reduce((acc, cur) => { return {...acc, [ctx.snakeCaseToCamelCase(cur[0])]: cur[1]} }, {});

ctx.jsonFromStyle = str => {
    // console.log(JSON.stringify(ctx.styleStringToJSON(str)));
    // return JSON.stringify(ctx.styleStringToJSON(str));
    console.log("JSON from style string:\n\n"ctx.util.inspect(ctx.styleStringToJSON(str)));

console.log("\x1b[1m\x1b[32m", "Call: jsonFromStyle(s: string)\n");

# Example Usage
# jsonFromStyle("fill:none;stroke:black;stroke-width:27.08px;")

After putting that in your .zshrc or copy pasting it into your terminal you can just run:


Then you will have a prompt where you can output JSON objects.

Node Is Powerful And Fast

I really was just posting this as a reminder to try do more shell style or system and utility scripting with Node.