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 .BeerJSONTypesA 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 HopAdditionTypeHopAdditionType(; 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 | |
|---|---|
| Name | RR Summer Bitter |
| Type | all grain |
| Author | RomaRoma |
| Style | English Best Bitter (Bitter Ale, AABC 2010) |
| Batch size | 40 l |
| Boil time | 60 min |
| Brewhouse efficiency | 75 % |
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])| Fermentable | Type | Amount | Color | Origin |
|---|---|---|---|---|
| Pale Malt, Maris Otter | grain | 7 kg | 3 Lovi | United Kingdom |
| Cara 50 | grain | 1 kg | 25.38 Lovi | Belgium |
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])| Hop | Alpha acid | Form | Amount | Added | Time |
|---|---|---|---|---|---|
| Target | 11 % | pellet | 0.04 kg | add_to_boil | 60 min |
| Goldings, East Kent | 5 % | pellet | 0.015 kg | add_to_boil | 30 min |
| Goldings, East Kent | 5 % | pellet | 0.015 kg | add_to_boil | 15 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])| Culture | Type | Form | Producer | Product |
|---|---|---|---|---|
| Windsor Yeast | ale | dry |
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 step | Type | Temperature | Time |
|---|---|---|---|
| Saccharification | infusion | 68.89 C | 40 min |
| Mash Out | temperature | 75.56 C | 10 min |
| Sparge | sparge | 75.56 C | 15 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.amountMassType(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])| Hop | Alpha acid | Amount | Added | Time |
|---|---|---|---|---|
| Chinook | 12.6 % | 0.02 kg | add_to_boil | 60 min |
| Ahtanum | 5.4 % | 0.0125 kg | add_to_boil | 60 min |
| Chinook | 12.6 % | 0.02 kg | add_to_boil | 30 min |
| Ahtanum | 5.4 % | 0.0125 kg | add_to_boil | 30 min |
| Chinook | 12.6 % | 0.0275 kg | add_to_boil | 0 min |
| Ahtanum | 5.4 % | 0.0125 kg | add_to_boil | 0 min |
| Simcoe | 12.8 % | 0.0125 kg | add_to_boil | 0 min |
| Nelson Sauvin | 12 % | 0.0125 kg | add_to_boil | 0 min |
| Chinook | 12.6 % | 0.0475 kg | add_to_boil | 10080 min |
| Ahtanum | 5.4 % | 0.0375 kg | add_to_boil | 10080 min |
| Simcoe | 12.8 % | 0.0375 kg | add_to_boil | 10080 min |
| Nelson Sauvin | 12 % | 0.02 kg | add_to_boil | 10080 min |
| Cascade | 6.8 % | 0.0375 kg | add_to_boil | 10080 min |
| Amarillo | 8.9 % | 0.01 kg | add_to_boil | 10080 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))])| Added | Total (kg) |
|---|---|
| add_to_boil | 0.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 | |
|---|---|
| Style | 16A Dry Stout (BJCP) |
| Original gravity | 1.035 sg – 1.05 sg |
| Final gravity | 1.007 sg – 1.011 sg |
| Bitterness | 30 IBUs – 50 IBUs |
| Color | 35 SRM – 200 SRM |
| Alcohol by volume | 3.2 % – 5.5 % |
| Carbonation | 1.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 | |
|---|---|
| calcium | 295 ppm |
| magnesium | 45 ppm |
| sodium | 55 ppm |
| sulfate | 725 ppm |
| chloride | 25 ppm |
| bicarbonate | 300 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._extraDict{String, Any} with 1 entry:
"pH" => 8.0A 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 | |
|---|---|
| Name | Super Hops |
| Origin | Planet Krypton |
| Type | bittering |
| Alpha acid | 4.5 % |
| Beta acid | 5.5 % |
| Substitutes | Goldings, Fuggles, Super Alpha |
| Total oil | |
| Myrcene | 24.2 % |
| Humulene | 2.34 % |
| Caryophyllene | 1.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_doctrueFor 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].amountMassType(MassUnitType("kg"), 0.05)try
@set recipe.batch_size.unit = VolumeUnitType("pint")
catch err
showerror(stdout, err)
endSchemaValidationError: 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)
endSchemaValidationError: 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)
endSchemaValidationError: 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"