【发布时间】:2017-08-17 11:46:08
【问题描述】:
我正在尝试将外部 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=]"}
Jekyll 的原生方法(用于本地文件)
{"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 我只是从原始要点中复制了它。在其中,在 if 语句之外还有另一个返回,它是一个告诉您错误的字符串。在我的情况下,我可能可以将其取下,但似乎没有必要。
-
我在您提供的代码中看不到“其他
return”。我也看不到@text的使用情况 -
@ashmaroli,this is the other return。我也不知道
@text的用途是什么,但它在原始代码和Jekyll example for Tags 中都有,所以我没有理由摆脱它。 -
@text 是你给标签的参数