From f971aebfb160691c4fbac083ac423ecef0a013ac Mon Sep 17 00:00:00 2001 From: liufengyun Date: Tue, 22 Oct 2013 18:04:32 +0800 Subject: [PATCH] support jsonify filter --- lib/jekyll/filters.rb | 10 ++++++++++ site/docs/templates.md | 11 +++++++++++ test/test_filters.rb | 11 +++++++++++ 3 files changed, 32 insertions(+) diff --git a/lib/jekyll/filters.rb b/lib/jekyll/filters.rb index b0ab8947..95ada0bd 100644 --- a/lib/jekyll/filters.rb +++ b/lib/jekyll/filters.rb @@ -1,4 +1,5 @@ require 'uri' +require 'json' module Jekyll module Filters @@ -148,6 +149,15 @@ module Jekyll end end + # Convert the input into json string + # + # input - The Array or Hash to be converted + # + # Returns the converted json string + def jsonify(input) + input.to_json + end + private def time(input) case input diff --git a/site/docs/templates.md b/site/docs/templates.md index 8ecff675..0417f2ab 100644 --- a/site/docs/templates.md +++ b/site/docs/templates.md @@ -173,6 +173,17 @@ common tasks easier.

+ + +

Data To JSON

+

Convert Hash or Array to JSON.

+ + +

+ {% raw %}{{ site.data.projects | jsonify }}{% endraw %} +

+ + diff --git a/test/test_filters.rb b/test/test_filters.rb index 6af0d705..28e9612d 100644 --- a/test/test_filters.rb +++ b/test/test_filters.rb @@ -98,5 +98,16 @@ class TestFilters < Test::Unit::TestCase should "escape space as %20" do assert_equal "my%20things", @filter.uri_escape("my things") end + + context "jsonify filter" do + should "convert hash to json" do + assert_equal "{\"age\":18}", @filter.jsonify({:age => 18}) + end + + should "convert array to json" do + assert_equal "[1,2]", @filter.jsonify([1, 2]) + assert_equal "[{\"name\":\"Jack\"},{\"name\":\"Smith\"}]", @filter.jsonify([{:name => 'Jack'}, {:name => 'Smith'}]) + end + end end end