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.rbindex 77e2534f168..9a70401daea 100644--- a/lib/onebox/json_ld.rb+++ b/lib/onebox/json_ld.rb@@ -4,6 +4,7 @@ module Oneboxclass JsonLd < Normalizer# Full schema.org hierarchy can be found here: https://schema.org/docs/full.htmlMOVIE_JSON_LD_TYPE = "Movie"+ SUPPORTED_TYPES = [MOVIE_JSON_LD_TYPE]def initialize(doc)@data = extract(doc)@@ -17,6 +18,11 @@ module Oneboxdoc.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_TYPEreturn Onebox::Movie.new(parsed_json).to_hdiff --git a/spec/lib/onebox/json_ld_spec.rb b/spec/lib/onebox/json_ld_spec.rbindex 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 doexpect(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+privatedef expected_movie_hash