0

I have a JSON file containing the following:

{
"colors": [
    {
        "name": "red",
        "hex": "#c33"
    },
    {
        "name": "blue",
        "hex": "#2f2"
    },
    {
        "name": "green",
        "hex": "#22f"
    }
]

}

The JSON needs to be in an array [] as I'm also using the same JSON for creating Handlebars templates and Handlebars seems to require the JSON to be like this(unless there's a way to get Handlebars to do otherwise?).

I'm using sass-json-vars to import the JSON file into my SASS :

@import 'variables.json';

Then what I want to do is loop through the JSON to create a list of SASS variables based on the values and names in the JSON.

So far the closest I can get is something like this:

@each $id, $val in $colors {

    @each $idB, $valB in $val {
        body {
            color: $idB;
        } 
    }
}

This is giving me both key and value:

body {
    color: #22f;
}

body {
    color: hex;
}

Which is obviously no good.

I can't find a way to use dot notation or something similar to reference the value matching a key and nesting loops like the above doesn't seem to work.

The kind of output in SASS i'm after is:

$red : #c33;
$blue : #2f2;
... etc

Can anyone help?

spengos
  • 133
  • 1
  • 10
  • [sass-json-vars](https://github.com/vigetlabs/sass-json-vars) README describes usage quite clearly, if that's what you're using. (Notice the difference between Sass versions before and after `3.3`.) – hon2a Jan 07 '16 at 11:22
  • sass-json-vars is working fine, this isn't the issue. The issue is I can't find a way to loop through the JSON in SASS and get the values I need in the right format. – spengos Jan 07 '16 at 11:25
  • Looks like I should have spent more time reading the question :) – hon2a Jan 07 '16 at 11:54

1 Answers1

1

If you're using Sass >= 3.3, something like

@function get-color($colors, $name) {
  @each $color in $colors {
    @if map-get($color, name) == $name {
      @return map-get($color, hex);
    }
  }
  @return null;
}

should do the trick. I haven't tested it though.

Usage:

.cls {
  color: get-color($colors, red);
}

You can't construct variable names programatically in Sass, so AFAIK there's no way to translate your structure into the desired set of global variables right there in your Sass file. You could transform it to a map and then just use map-get though (if the above solution works, this should be a trivial exercise).

hon2a
  • 7,006
  • 5
  • 41
  • 55
  • Hmmm, well if I can't programatically create variables in SASS then what I want isn't going to work. Oh well. Think I'll need a different approach entirely. Many thanks for looking anyway! – spengos Jan 07 '16 at 12:05