BeerJSON

BeerJSON is an open format for beer recipes and brewing data: fermentables, hops, cultures, water profiles, styles, equipment, and the mash, boil, fermentation and packaging procedures. Its schema (version 1.0.1 here, in examples/beerjson-1.0.1/) is spread over twenty files, with 92 types once translated.

The code on this page is run when the documentation is built, on sample documents from the BeerJSON repository (in test/beerjson-1.0.1-samples/).

Generating the types

The types are generated into a directory, with one file per schema file:

schema = joinpath(ROOT, "examples", "beerjson-1.0.1", "json", "beer.json")
main = generate_module(schema, joinpath(mktempdir(), "BeerJSONTypes");
                       root_name = "BeerJSON", split = true)
readdir(dirname(main))
22-element Vector{String}:
 "BeerJSONTypes.jl"
 "beer.jl"
 "boil.jl"
 "boil_step.jl"
 "culture.jl"
 "equipment.jl"
 "fermentable.jl"
 "fermentation.jl"
 "fermentation_step.jl"
 "hop.jl"
 ⋮
 "misc.jl"
 "packaging.jl"
 "packaging_vessel.jl"
 "recipe.jl"
 "runtime.jl"
 "runtime_validation.jl"
 "style.jl"
 "timing.jl"
 "water.jl"
include(main)
using .BeerJSONTypes

A BeerJSON document is an object with a single property, beerjson, which holds the version of the format and lists of records: recipes, fermentables, hop varieties, styles, water profiles...

fieldnames(BeerJSONContent)
(:version, :timing_object, :fermentables, :miscellaneous_ingredients, :hop_varieties, :cultures, :profiles, :styles, :mashes, :fermentations, :recipes, :equipments, :boil, :packaging)

The types follow the schema. For instance, a hop addition in a recipe:

@doc HopAdditionType
HopAdditionType(; kwargs...)
HopAdditionType{I, T}(; kwargs...)

HopAdditionType collects the attributes of each hop ingredient for use in a recipe hop bil.

Integers are stored as I <: Integer and other numbers as T <: Real; by default, Int64 and Float64.

Fields

  • name::String (required)

  • producer::Union{Nothing, String}

  • product_id::Union{Nothing, String}

  • origin::Union{Nothing, String}

  • year::Union{Nothing, String}

  • form::Union{Nothing, HopVarietyFormEnum}

  • alpha_acid::PercentType{I, T} (required)

  • beta_acid::Union{Nothing, PercentType{I, T}}

  • timing::TimingType{I, T} (required): The timing object fully describes the timing of an addition with options for basis on time, gravity, or pH at any process step.

  • amount::Union{VolumeType{I, T}, MassType{I, T}} (required)

  • _extra::Dict{String, Any}: additional properties, not described in the schema

A recipe

Let us read a recipe, converted from a BeerXML file of the Brewtarget examples:

doc = readjson(RootType, joinpath(SAMPLES, "converted", "RRSummerBitter.json"))
recipe = only(doc.beerjson.recipes)
table(["Recipe", ""], [
    ["Name", recipe.name],
    ["Type", recipe.type],
    ["Author", recipe.author],
    ["Style", "$(recipe.style.name) ($(recipe.style.category), $(recipe.style.style_guide))"],
    ["Batch size", q(recipe.batch_size)],
    ["Boil time", q(recipe.boil.boil_time)],
    ["Brewhouse efficiency", q(recipe.efficiency.brewhouse)],
])
Recipe
NameRR Summer Bitter
Typeall grain
AuthorRomaRoma
StyleEnglish Best Bitter (Bitter Ale, AABC 2010)
Batch size40 l
Boil time60 min
Brewhouse efficiency75 %

Its ingredients:

ingredients = recipe.ingredients
table(["Fermentable", "Type", "Amount", "Color", "Origin"],
      [[f.name, f.type, q(f.amount), q(f.color), s(f.origin)]
       for f in ingredients.fermentable_additions])
FermentableTypeAmountColorOrigin
Pale Malt, Maris Ottergrain7 kg3 LoviUnited Kingdom
Cara 50grain1 kg25.38 LoviBelgium
table(["Hop", "Alpha acid", "Form", "Amount", "Added", "Time"],
      [[h.name, q(h.alpha_acid), s(h.form), q(h.amount), s(h.timing.use), q(h.timing.time)]
       for h in ingredients.hop_additions])
HopAlpha acidFormAmountAddedTime
Target11 %pellet0.04 kgadd_to_boil60 min
Goldings, East Kent5 %pellet0.015 kgadd_to_boil30 min
Goldings, East Kent5 %pellet0.015 kgadd_to_boil15 min
table(["Culture", "Type", "Form", "Producer", "Product"],
      [[c.name, c.type, c.form, s(c.producer), s(c.product_id)]
       for c in ingredients.culture_additions])
CultureTypeFormProducerProduct
Windsor Yeastaledry

And its mash:

table(["Mash step", "Type", "Temperature", "Time"],
      [[m.name, m.type, q(m.step_temperature), q(m.step_time)] for m in recipe.mash.mash_steps])
Mash stepTypeTemperatureTime
Saccharificationinfusion68.89 C40 min
Mash Outtemperature75.56 C10 min
Spargesparge75.56 C15 min

Values are typed: the amount of a hop is a mass or a volume (a oneOf in the schema), with units from an enumeration:

hop = first(ingredients.hop_additions)
hop.amount
MassType(MassUnitType("kg"), 0.04)

A hop schedule

The BrewDog Punk IPA recipe has fourteen hop additions:

punk = only(readjson(RootType, joinpath(SAMPLES, "converted", "punk-ipa-2010-current.json")).beerjson.recipes)
table(["Hop", "Alpha acid", "Amount", "Added", "Time"],
      [[h.name, q(h.alpha_acid), q(h.amount), s(h.timing.use), q(h.timing.time)]
       for h in punk.ingredients.hop_additions])
HopAlpha acidAmountAddedTime
Chinook12.6 %0.02 kgadd_to_boil60 min
Ahtanum5.4 %0.0125 kgadd_to_boil60 min
Chinook12.6 %0.02 kgadd_to_boil30 min
Ahtanum5.4 %0.0125 kgadd_to_boil30 min
Chinook12.6 %0.0275 kgadd_to_boil0 min
Ahtanum5.4 %0.0125 kgadd_to_boil0 min
Simcoe12.8 %0.0125 kgadd_to_boil0 min
Nelson Sauvin12 %0.0125 kgadd_to_boil0 min
Chinook12.6 %0.0475 kgadd_to_boil10080 min
Ahtanum5.4 %0.0375 kgadd_to_boil10080 min
Simcoe12.8 %0.0375 kgadd_to_boil10080 min
Nelson Sauvin12 %0.02 kgadd_to_boil10080 min
Cascade6.8 %0.0375 kgadd_to_boil10080 min
Amarillo8.9 %0.01 kgadd_to_boil10080 min

The total amount of hops, by addition:

total = Dict{String, Float64}()
for h in punk.ingredients.hop_additions
    total[string(h.timing.use)] = get(total, string(h.timing.use), 0.0) + h.amount.value
end
table(["Added", "Total (kg)"], [[k, round(v; digits = 3)] for (k, v) in sort(collect(total))])
AddedTotal (kg)
add_to_boil0.32

A style

Styles describe the ranges of the vital statistics of a beer:

style = only(readjson(RootType, joinpath(SAMPLES, "real", "StyleDryIrishStoutWithAllFields.json")).beerjson.styles)
table(["Style", ""], [
    ["Style", "$(style.category_number)$(style.style_letter) $(style.name) ($(style.style_guide))"],
    ["Original gravity", r(style.original_gravity)],
    ["Final gravity", r(style.final_gravity)],
    ["Bitterness", r(style.international_bitterness_units)],
    ["Color", r(style.color)],
    ["Alcohol by volume", r(style.alcohol_by_volume)],
    ["Carbonation", r(style.carbonation)],
])
Style
Style16A Dry Stout (BJCP)
Original gravity1.035 sg – 1.05 sg
Final gravity1.007 sg – 1.011 sg
Bitterness30 IBUs – 50 IBUs
Color35 SRM – 200 SRM
Alcohol by volume3.2 % – 5.5 %
Carbonation1.6 vols – 2.1 vols
print(style.overall_impression)
Full body perception due to flaked barley, though starting gravity may be low. Dry roasted flavor.

A water profile

water = only(readjson(RootType, joinpath(SAMPLES, "real", "SampleWaterProfile.json")).beerjson.profiles)
ions = [:calcium, :magnesium, :sodium, :sulfate, :chloride, :bicarbonate]
table(["$(water.name)", ""], [[ion, q(getfield(water, ion))] for ion in ions])
Burton on Trent, UK
calcium295 ppm
magnesium45 ppm
sodium55 ppm
sulfate725 ppm
chloride25 ppm
bicarbonate300 ppm

This document also gives the pH of the water, which version 1.0.1 of the schema does not describe for water profiles. It is allowed, since the schema does not forbid additional properties there, so it is kept in the _extra field, and written back:

water._extra
Dict{String, Any} with 1 entry:
  "pH" => 8.0

A hop variety

Records for ingredients have more information than their additions to a recipe:

variety = first(readjson(RootType, joinpath(SAMPLES, "real", "HopRecordWithAllFields.json")).beerjson.hop_varieties)
oil = variety.oil_content
table(["Hop variety", ""], [
    ["Name", variety.name],
    ["Origin", s(variety.origin)],
    ["Type", s(variety.type)],
    ["Alpha acid", q(variety.alpha_acid)],
    ["Beta acid", q(variety.beta_acid)],
    ["Substitutes", s(variety.substitutes)],
    ["Total oil", q(oil.total_oil_ml_per_100g)],
    ["Myrcene", q(oil.myrcene)],
    ["Humulene", q(oil.humulene)],
    ["Caryophyllene", q(oil.caryophyllene)],
    ["Farnesene", q(oil.farnesene)],
])
Hop variety
NameSuper Hops
OriginPlanet Krypton
Typebittering
Alpha acid4.5 %
Beta acid5.5 %
SubstitutesGoldings, Fuggles, Super Alpha
Total oil
Myrcene24.2 %
Humulene2.34 %
Caryophyllene1.23 %
Farnesene

Creating and writing a document

New records are created with keyword constructors, which accept plain values, and validate them. A hop addition for a dry hop:

dry_hop = HopAdditionType(
    name = "Cascade",
    alpha_acid = (unit = "%", value = 5.5),
    form = "pellet",
    amount = Dict("unit" => "g", "value" => 50),
    timing = Dict("use" => "add_to_fermentation", "duration" => Dict("unit" => "day", "value" => 4)),
)
print(tojson(dry_hop; pretty = true))
{
  "name": "Cascade",
  "form": "pellet",
  "alpha_acid": {
    "unit": "%",
    "value": 5.5
  },
  "timing": {
    "duration": {
      "unit": "day",
      "value": 4
    },
    "use": "add_to_fermentation"
  },
  "amount": {
    "unit": "g",
    "value": 50
  }
}

Structs are immutable, so to change a record, build a new one. setfields returns a copy with some fields changed, validating them as the constructor does. Here we add the dry hop to the recipe and double the batch size, and then write the recipe to a new BeerJSON document:

new_recipe = setfields(recipe;
    name = recipe.name * " (dry hopped)",
    batch_size = setfields(recipe.batch_size; value = 2 * recipe.batch_size.value),
    ingredients = setfields(ingredients; hop_additions = [ingredients.hop_additions; dry_hop]))
new_doc = BeerJSON(beerjson = BeerJSONContent(version = 1.0, recipes = [new_recipe]))
file = writejson(joinpath(mktempdir(), "dry-hopped.json"), new_doc)
readjson(RootType, file) == new_doc
true

For changes deep inside a document, the generated structs work with Accessors.jl, whose @set rebuilds the values along the way, validating them:

using Accessors
bigger = @set recipe.ingredients.hop_additions[1].amount.value = 0.05
bigger.ingredients.hop_additions[1].amount
MassType(MassUnitType("kg"), 0.05)
try
    @set recipe.batch_size.unit = VolumeUnitType("pint")
catch err
    showerror(stdout, err)
end
SchemaValidationError: invalid value "pint" for `VolumeUnitType`; allowed values are "ml", "l", "tsp", "tbsp", "floz", "cup", "pt", "qt", "gal", "bbl", "ifloz", "ipt", "iqt", "igal", "ibbl"

Invalid values are rejected, when constructing a value or reading a document:

try
    VolumeType(unit = "litre", value = 20)
catch err
    showerror(stdout, err)
end
SchemaValidationError: invalid value "litre" for `VolumeUnitType`; allowed values are "ml", "l", "tsp", "tbsp", "floz", "cup", "pt", "qt", "gal", "bbl", "ifloz", "ipt", "iqt", "igal", "ibbl"
try
    HopAdditionType(name = "Cascade", alpha_acid = Dict("unit" => "%", "value" => 5.5),
                    timing = Dict(), amount = Dict("unit" => "cm", "value" => 50))
catch err
    showerror(stdout, err)
end
SchemaValidationError: value does not match any of the options of `Union{MassType, VolumeType}`:
  `Main.BeerJSONTypes.MassType{Int64, Float64}`: invalid value "cm" for `MassUnitType`; allowed values are "mg", "g", "kg", "lb", "oz"
  `Main.BeerJSONTypes.VolumeType{Int64, Float64}`: invalid value "cm" for `VolumeUnitType`; allowed values are "ml", "l", "tsp", "tbsp", "floz", "cup", "pt", "qt", "gal", "bbl", "ifloz", "ipt", "iqt", "igal", "ibbl"

Reading every sample

Every sample document of BeerJSON 1.0.1 can be read, and written back unchanged:

using JSON
canon(x::AbstractDict) = Dict(String(k) => canon(v) for (k, v) in x)
canon(x::AbstractVector) = Any[canon(v) for v in x]
canon(x::Real) = x isa Bool ? x : Float64(x)
canon(x) = x
files = [joinpath(dir, f) for dir in readdir(SAMPLES; join = true) if isdir(dir)
         for f in readdir(dir) if endswith(f, ".json")]
unchanged = count(files) do f
    canon(JSON.parse(tojson(readjson(RootType, f)))) == canon(JSON.parse(read(f, String)))
end
"$unchanged of $(length(files)) documents read and written back unchanged"
"43 of 43 documents read and written back unchanged"