2017-08-17 19 views
0

我試圖將外部JSON數據提取到Jekyll中,但事情並沒有解決。外部JSON數據無法在Jekyll中輸出任何東西

我發現this code (link to a gist),這是另一個要點的分支......這只是增加了外部方法(「來自url」)。

我試圖變身那到我自己的標籤插件(或什麼都他們被稱爲),爲了簡化它,並儘可能解決一些問題:

_plugins/externaljson.rb

require 'json' 
require 'net/http' 

module ExternalJSON 
    class ExternalJSON_tag < Liquid::Tag 

    def initialize(tag_name, text, tokens) 
     super 
     @text = text 
    end 

    def render(context) 

     if /(.+) from (.+)/.match(@text) 
     url = context[$2].strip 
      uri = URI(url) 
      response = Net::HTTP.get(uri) 
      data = JSON.parse(response) 
      context[$1] = JSON data 
      return '' 
     end 

    end 
    end 
end 

Liquid::Template.register_tag('externalJSON', ExternalJSON::ExternalJSON_tag) 

...但我沒有真正解決我的所有問題,也沒有從中學到很多東西。我認爲我學到的唯一一件事就是問題可能出現在解析ruby文件和jekyll文件之間。

我跑使用上述(↑)標記插件代碼這個測試:

--- 
layout: default 
--- 

<!-- Using the code I modified --> 
<!-- This capture exists to combine a string and a variable, but it's just a static url for the purposes of this example --> 
{% capture myUrl %} 
    https://api.guildwars2.com/v2/recipes/2889 
{% endcapture %} 

{% externalJSON jsonData from myUrl %} 
{% for data in jsonData %} 
    {{ data}} 
{% endfor %} 

<!-- Jekyll's native way of handling local data files --> 
<!-- I just saved that json data from the url above(↑) locally for this one --> 
{% for data in site.data.example %} 
    {{ data }} 
{% endfor %} 

這個測試使我意識到,這兩種方法的輸出數據略有不同。

我的外部嘗試:

{"type":"Meal","output_item_id":12210,"output_item_count":2,"min_rating":0,"time_to_craft_ms":1000,"disciplines":["Chef"],"flags":[],"ingredients":[{"item_id":24359,"count":1},{"item_id":12132,"count":1}],"id":2889,"chat_link":"[&CUkLAAA=]"} 

哲基爾的本地方法(對於本地文件)

{"type"=>"Meal", "output_item_id"=>12210, "output_item_count"=>2, "min_rating"=>0, "time_to_craft_ms"=>1000, "disciplines"=>["Chef"], "flags"=>[], "ingredients"=>[{"item_id"=>24359, "count"=>1}, {"item_id"=>12132, "count"=>1}], "id"=>2889, "chat_link"=>"[&CUkLAAA=]"} 

如果我嘗試,例如做{{data.type}},我的外部嘗試不會返回任何結果,而Jekyll方法就像它應該返回值一樣。我只是無法弄清楚如何改變格式或什麼是缺失的部分。

我在做什麼錯?

+0

''return'''看起來很可疑 – ashmaroli

+0

@ashmaroli我剛剛從原來的要點複製過來。其中,if語句之外還有一個返回字符串,告訴你一個錯誤。在我的情況下,我可能會把它拿走,但似乎沒有必要。 – Joonas

+0

我在你提供的代碼中看不到「other'return'」。我看不到'@ text'是如何使用 – ashmaroli

回答

2

取代你render(context)有以下幾點:

def render(context) 
    if /(.+) from url (.+)/.match(@text) 
    resp = Net::HTTP.get_response(URI($2.strip)) 
    data = resp.body 
    context[$1] = JSON data 
    nil 
    else 
    # syntax error 
    raise ArgumentError, 'ERROR:bad_syntax' 
    end 
end 

然後調用data像這樣:

{% externalJSON data from url http://foo.json %} 

這將爲您提供可調用,以呈現個人密鑰的data對象。

如果數據是一個數組,循環通過的元素,並調用所需的鍵

{% for entry in data %} 
    {{ entry.type }} 
{% endfor %} 

如果數據是一個對象(散列),直接調用鍵。

{{ data.type }}