Sort JSON-LD data by key

Deterministic output is desired to improve diffability between builds.
If the output randomly changes order each time it's built, then every
page on a given site will change with every Jekyll build. Tools like
rsync and git which can diff files will always show a change even when
the content hasn't truly changed.
This commit is contained in:
Parker Moore 2022-01-30 20:31:59 -08:00
parent c658a8dd9d
commit af87d9fbe8
No known key found for this signature in database
GPG Key ID: 01653849488D3BB8
2 changed files with 11 additions and 2 deletions

View File

@ -87,8 +87,13 @@ module Jekyll
alias_method :mainEntityOfPage, :main_entity
private :main_entity
def to_json
to_h.compact.to_json
# Returns a JSON-encoded object containing the JSON-LD data.
# Keys are sorted.
def to_json(state = nil)
keys.sort.each_with_object({}) do |(key, _), result|
v = self[key]
result[key] = v if v # don't write if value is nil
end.to_json(state)
end
private

View File

@ -30,6 +30,10 @@ RSpec.describe Jekyll::SeoTag do
expect(output).to match(%r!Jekyll v#{version}!i)
end
it "outputs JSON sorted by key" do
expect(json.strip).to eql('{"@context":"https://schema.org","@type":"WebPage","url":"/page.html"}')
end
it "outputs valid HTML" do
site.process
options = {