FIX: Handle sites with more than 1 JSON-LD element (#17095)

A followup to #17007
This commit is contained in:
Jarek Radosz
2022-06-15 02:55:55 +02:00
committed by GitHub
parent 4d3c1ceb44
commit f723b4c322
2 changed files with 21 additions and 20 deletions

View File

@@ -12,32 +12,25 @@ module Onebox
private
def extract(doc)
extracted_json = extract_json_from(doc)
parsed_json = parse_json(extracted_json)
return {} if Onebox::Helpers::blank?(doc)
doc.css('script[type="application/ld+json"]').each do |element|
parsed_json = parse_json(element.text)
extracted =
case parsed_json["@type"]
when MOVIE_JSON_LD_TYPE
Onebox::Movie.new(parsed_json)
else
{}
return Onebox::Movie.new(parsed_json).to_h
end
end
extracted.to_h
end
def extract_json_from(doc)
return {} if Onebox::Helpers::blank?(doc)
json_ld = doc.search('script[type="application/ld+json"]').text
return {} if Onebox::Helpers::blank?(json_ld)
json_ld
{}
end
def parse_json(json)
begin
JSON[json]
rescue JSON::ParserError => e
Discourse.warn_exception(e, message: "Error parsing JSON-LD json: #{json}")
Discourse.warn_exception(e, message: "Error parsing JSON-LD: #{json}")
{}
end
end