我试图将外部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方法就像它应该返回值一样。我只是无法弄清楚如何改变格式或什么是缺失的部分。
我在做什么错?
''return'''看起来很可疑 – ashmaroli
@ashmaroli我刚刚从原来的要点复制过来。其中,if语句之外还有一个返回字符串,告诉你一个错误。在我的情况下,我可能会把它拿走,但似乎没有必要。 – Joonas
我在你提供的代码中看不到“other'return'”。我看不到'@ text'是如何使用 – ashmaroli