Giter VIP home page Giter VIP logo

sassyjson's Introduction

SassyJSON NPM version Gem Version

⚠️ SassyJSON was an experimental project. It is not meant to be used in production. If you need to transit JSON data from and to your Sass layer, have a look into Eyeglass and Sassport.

SassyJSON is a Sass-powered API for JSON. It provides you the classic json-encode and json-decode directly from your Sass files. We'll leave you the only judges of the point of this.

Install

SassyJSON is available on npm or as a Ruby Gem.

Git

git clone https://github.com/KittyGiraudel/SassyJSON.git && cd SassyJSON

npm

npm install sassyjson --save-dev

Compass extension

  1. gem install SassyJSON
  2. Add require 'SassyJSON' to your config.rb
  3. Import it in your stylesheets with @import 'SassyJSON'

Sass

If you only want to play around the code without cloning the repo or using npm, you can find a single file containing the whole API in the dist folder.

Also, SassyJSON is available at Sassmeister.

Example

Encoding Sass to JSON

Sass

$map: ((a: (1 2 ( b : 1 )), b: ( #444444, false, ( a: 1, b: test ) ), c: (2 3 4 string)));

@include json-encode($map);

CSS

/*! json-encode: '{"a": [1, 2, {"b": 1}], "b": ["#444444", false, {"a": 1, "b": "test"}], "c": [2, 3, 4, "string"]}' */

body::before {
  display:block;
  width:0;height:0;
  overflow:hidden;
  content: '{"a": [1, 2, {"b": 1}], "b": ["#444444", false, {"a": 1, "b": "test"}], "c": [2, 3, 4, "string"]}';
}

head {
  font-family: '{"a": [1, 2, {"b": 1}], "b": ["#444444", false, {"a": 1, "b": "test"}], "c": [2, 3, 4, "string"]}';
}

@media -json-encode {
  json {
    json: '{"a": [1, 2, {"b": 1}], "b": ["#444444", false, {"a": 1, "b": "test"}], "c": [2, 3, 4, "string"]}';
  }
}

If you want to restrict the output to only one of the three drivers (comment, media query or regular output) you can pass a flag as the second parameter with one of the four following keywords: all, comment, media or regular. Default is all.

Decoding JSON to Sass

$json-decode: json-decode('{"a": [1, 2, {"b": 1}], "b": ["#444444", false, {"a": 1, "b": "test"}], "c": [2, 3, 4, "string"]}');
// ("a": 1 2 ("b": 1), "b": #444444 false ("a": 1, "b": "test"), "c": 2 3 4 "string")

Importing and decoding a JSON file

To importe and decode an external .json file directly into a Sass variable:

@import 'SassyJSON'; // Import SassyJSON first!
@import 'relative/path/to/file.json?variable-name';
// Do something with $variable-name

Important:

  • the path to the JSON file is relative to importing file
  • the get parameter is the variable name to use it in Sass

Requirements

All you need is a clean version of Sass 3.3. Otherwise it's just pure Sass madness.

Development

You need

  • NodeJS
  • Ruby
  • Sass 3.3 via gem install sass --pre
  • grunt-cli via npm install -g grunt-cli

How to

  1. Fork this repository
  2. Run npm install
  3. grunt dev
  4. Make your changes + write tests
  5. Commit + Pull request

Credits

sassyjson's People

Contributors

crocodillon avatar esr360 avatar fweinb avatar kittygiraudel avatar p2media avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sassyjson's Issues

Export map to json file.

Ran into a use case for this. I needed to get a list of selectors that use a certain mixin from a Sass file for use in a PHP class (via parsing a JSON map to an associative array). So, came up with a somewhat hacky solution, as I don't know Ruby much at all.

Ruby

# -------------------------------------------------------------------------------------------------------
# SassyJSON : write json file from passed Sass map to path/to/filename
# -------------------------------------------------------------------------------------------------------
# @param $path [string] : directory path to write $string
# @param $filename [string] : file name to write to $path
# @param $string [string] : json to write to $filename
# -------------------------------------------------------------------------------------------------------

module Sass::Script::Functions
    def SassyJSON_export(path, filename, string)
        # define root path up to current folder
        root = File.dirname(options[:filename] || ".")
        # open file [create new file if file does not exist], write $string to $root/$path/$filename
        File.open("#{root}/#{path}/#{filename}.json", "w") { |f| f.write(string) }
        # return string for use in css
        return string
    end
end

Sass

// ./sass/style.scss

@mixin json_export($path, $filename, $map) {
    @at-root {
        %json_export {
            content: "#{SassyJSON_export(unquote($path), unquote($filename), unquote(json_encode($map)))}";
        }
    }
}

$map: (
    hello: world,
);

@include json_export("../json", "config", $map);

New JSON file in ./json/config.json

{"hello": "world"}

The json_export() mixin takes a directory $path, $filename, and a Sass $map as arguments, then it converts the $map to a JSON map with the json_encode() function, then Ruby creates a new file, and writes the contents of the json string to it. I'm sure all of these functions could be improved, but it is still a nice proof of concept.

Might as well, right?

New release?

Any planned schedule for an npm release? The recently-fixed quoting bug is a deal-breaker for use with libsass.

Thanks! (We're using this project in our recent work on living styleguides...)

Lengths and colors

When decoding something like "red" or "#000" or "42px". Shouldn't we convert this to color and number type?

Import a JSON file

It would be neat if we could find a way to import a .json file in some way. Maybe with a Grunt task or something?

Updating to Sass 3.3.0.rc.3 will fail

I just tried to Update to Sass 3.3.0.rc.3
Bootcamp dosen't really work right (had do comment some tests out).

But these tests are failing hard:

The _json-decode--number function should properly decode numbers with exponents
  ✗ Expected 100 to equal 1
  ✗ Expected 100 to equal 1
  ✗ Expected 100 to equal 1
  ✗ Expected 100 to equal 1
  Test failed


The _json-decode--number function should properly decode numbers with negative exponents
  ✗ Expected 100 to equal 1
  ✗ Expected 100 to equal 1
  Test failed

See http://sassmeister.com/gist/8941823
We need to make this working again!

String decode

I have updated the string decode function to escape \r and \n. I also added a helper function for this. By the way I also made it work for empty strings.

However I couldn't manage to write tests for this. If you could have a glance @FWeinb.

Also, I haven't found a way to check for \". The problem I encountered is the following:

$string: 'test\"test';
$index: str-index($string, '"'); // 6
$slice: str-slice($string, $index - 1, $index); // t"

When I slice right before the quote, I get a t and not a backslash. Meanwhile when I do the exact same thing with \r instead of \", it works very well. It looks like we can't detect that this way. :(

Can't get importer to function

I feel I might just simply be misunderstanding the installation instructions --

I get the following error when attempting to import a valid json file to a sass variable:

error style.scss (Line 5: File to import not found or unreadable: ../../../config.json?pp-config.

I grabbed a copy of the _SassyJSON.scss file from the dist folder and included it before attempting to import my json file -- do I need to install this as a node package in order to get the importer to work properly?

My json file is valid and I've tried with other files, and also with files in the same directory as the importing file in case the path I'm using is wrong somehow.

Thanks

Add tests

I'd like to see moar tests, even very nasty one. Especially when it comes to invalid JSON; I want to make sure we cover all cases and don't fall into a compilation issue whenever we try decoding invalid JSON.

Error returns

I'm teared in half between returning false and returning the error message as a string when something went wrong.

What's best between:

$json: json-decode('stuff');
// false
// ERROR::Unexpected token `s`.

In case you prefer the second one, we could find an appropriate syntax for the error thing.

`json-encode` issues

Three things to do:

  • Add some tests, even weird ones
  • Fix the failed test in _list.scss
  • See why commented lines in _map.scss prevent from compiling

Use @media for json-encode mixin

I'm not sure about previous discussion on this topic. However the current way of storing json doesn't seem all that safe if it were needed on an actual website.

This is how sass's debug info works:

@media -sass-debug-info {
  filename {
    font-family: file\:\/\/\/Users\/thejameskyle\/git\/thejameskyle\/bootcamp\/node_modules\/sassyjson\/src\/encode\/mixins\/_json\.scss;
  }

  line {
    font-family: \000037;
  }
}

I'm proposing making the json encode mixin work the same way:

@media -json-encode {
  json {
    font-family: "[1, 2, 3]";
  }
}

This would prevent any possible collision of actual styles.

[BUG] Keys and values are double qouted

Scss file:

$map: (key1: val1, key2: (
    subkey21: val21,
    number: 1123,
    colorval: #123,
));

body:before {
    font-family: json-encode($map);
}

CSS file:

body:before  {
    font-family: "{'\"key1\"': '\"val1\"', '\"key2\"': {'\"subkey21\"': '\"val21\"', '\"number\"': 1123, '\"colorval\"': '\"#123\"'}}";
}

Using:

node-sass   3.4.0-beta1 (Wrapper)   [JavaScript]
libsass     3.3.0-beta2 (Sass Compiler) [C/C++]

Add to npm

I think it is enough to push the single file version to npm.

Add Gem building to build task

It would be cool to test if the gem build and install works before bumping every version. Could we add something like this to a task?

gem build SassyJSON.gemspec
gem install SassyJSON-x.y.z.gem

Encoded lists only contain the first element (libSass 3.3)

This is not a bug in SassyJSON, rather than it's a bug in libSass.
There is already an issue for this: sass/libsass#1566
I just want to inform you.

scss:

$map: (first, second, third, fourth);

body {
    content: call("_json-encode--list", $map);
    font-family: _json-encode--list($map);
}

CSS:

body {
    content: '["first"]';
    font-family: '["first", "second", "third", "fourth"]'
}

Using:

node-sass   3.4.0-beta1 (Wrapper)   [JavaScript]
libsass     3.3.0-beta2 (Sass Compiler) [C/C++]

Problem with "n" and "r"

Hi Hugo,

I hope you're okay since the last time.

I try to share my breakpoints between Sass and JS.
So I came to your SassyJSON! Thanks for the great job!

I just have some problems when I use a "r" or a "n" inside a 'key string', like this :

@import "SassyJSON";
$foo: json-decode('{"narrow": "768px"}');
.bar {
  output: map-keys($foo); // "\a     a\a     \a     ow"
}

Any idea?
Thierry

Throws error when importing valid indented JSON

This seems to be throwing an error for an unknown reason. I tried looking through your source to see what was going wrong, but couldn't pinpoint the issue. It's not trailing space, or invalid JSON. Ran it through a JSON linter and everything came back okay. Ignore the comments in the code.

// Throws: "WARNING: ERROR::3::Unexpected token `   ` in object literal."
{
    "config": {
        "desktop": {
            "columns": 16,
            "breakpoint": "1280px"
        },
        "laptop": {
            "columns": 12,
            "breakpoint": "960px"
        },
        "tablet": {
            "columns": 8,
            "breakpoint": "640px"
        },
        "mobile": {
            "columns": 4,
            "breakpoint": "320px"
        },
        "settings": {
            "default": "desktop",
            "grid": "fluid",
            "gutter": "10px",
            "float-style": "left",
            "max-width": "1440px",
            "center-container": true,
            "border-box-sizing": true,
            "debug-mode": true
        }
    }
}
// Decodes perfectly:
{"config": {"desktop": {"columns": 16, "breakpoint": "1280px"}, "laptop": {"columns": 12, "breakpoint": "960px"}, "tablet": {"columns": 8, "breakpoint": "640px"}, "mobile": {"columns": 4, "breakpoint": "320px"}, "settings": {"default": "desktop", "grid": "fluid", "gutter": "10px", "float-style": "left", "max-width": "1440px", "center-container": true, "border-box-sizing": true, "debug-mode": true}}}

What's going on here? Is it the tabs?

Update README.md

Add development instructions + explain how to get SassyJson from npm

Invalid CSS after " @each $key"

When I try to import my JSON I get this error:

Invalid CSS after "  @each $key": expected "in", was ", $value in $map {"

Is there a specific sass version needed?

(also I put my require in config.ru since my rails4 app doesnt seem to have a config.rb?)

Pow function

I added a pow helper function to deal with exponents in numbers. Should we use the one from SassyMap/Compass as a dependency instead?

I think using our own is better than including a dependency but I may be wrong.

Bower package?

Are you will to publish SassyJSON as Bower package (or accept PR for that)?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.