Skip to content

A platform for community discussion. Free, open, simple.

FIX: Use first supported type item when JSON-LD returns array (#17217)

Penar Musaraj3baefa25b581
diff --git a/lib/onebox/json_ld.rb b/lib/onebox/json_ld.rb
index 77e2534f168..9a70401daea 100644
--- a/lib/onebox/json_ld.rb
+++ b/lib/onebox/json_ld.rb
@@ -4,6 +4,7 @@ module Onebox
class JsonLd < Normalizer
# Full schema.org hierarchy can be found here: https://schema.org/docs/full.html
MOVIE_JSON_LD_TYPE = "Movie"
+ SUPPORTED_TYPES = [MOVIE_JSON_LD_TYPE]
def initialize(doc)
@data = extract(doc)
@@ -17,6 +18,11 @@ module Onebox
doc.css('script[type="application/ld+json"]').each do |element|
parsed_json = parse_json(element.text)
+ if parsed_json.kind_of?(Array)
+ parsed_json = parsed_json.detect { |x| SUPPORTED_TYPES.include?(x["@type"]) }
+ return {} if !parsed_json
+ end
+
case parsed_json["@type"]
when MOVIE_JSON_LD_TYPE
return Onebox::Movie.new(parsed_json).to_h
diff --git a/spec/lib/onebox/json_ld_spec.rb b/spec/lib/onebox/json_ld_spec.rb
index 00d84d4deef..0155b604351 100644
--- a/spec/lib/onebox/json_ld_spec.rb
+++ b/spec/lib/onebox/json_ld_spec.rb
@@ -47,6 +47,27 @@ describe Onebox::JsonLd do
expect(json_ld.data).to eq(expected_movie_hash)
end
+ it 'returns first supported type when JSON-LD is an array' do
+ array_json = '<script type="application/ld+json">[{"@type": "Something Else"}, {"@context":"https://schema.org","@type":"Movie","url":"/title/tt2358891/","name":"La grande bellezza","alternateName":"The Great Beauty"}]</script>'
+ doc = Nokogiri::HTML(array_json)
+ json_ld = described_class.new(doc)
+ expect(json_ld.data).to eq({
+ description: nil,
+ duration: nil,
+ genres: nil,
+ image: nil,
+ name: "La grande bellezza",
+ rating: nil
+ })
+ end
+
+ it 'does not fail when JSON-LD returns an array with no supported types' do
+ array_json = '<script type="application/ld+json">[{"@type": "Something Else"}, {"@context":"https://schema.org","@type":"Nothing"},{"@context":"https://schema.org"}]</script>'
+ doc = Nokogiri::HTML(array_json)
+ json_ld = described_class.new(doc)
+ expect(json_ld.data).to eq({})
+ end
+
private
def expected_movie_hash