# schema.org JSON-LD

> Reference for findRecipeJsonLd, fromJsonLd, and toJsonLd, which read recipes from schema.org Recipe JSON-LD and write them as JSON-LD.

Source: https://recipe-book.siraj.page/reference/core/schema-org/

Use these exports from `@recipe-book/core/schema-org` to import the [schema.org Recipe](https://schema.org/Recipe) JSON-LD that recipe sites publish, and to write your own recipes as JSON-LD, the structured data that search engines read to show recipes as rich results. They use no DOM, so they run in Node, edge runtimes, and browsers. The subpath shares its code with `@recipe-book/core`, so its errors are instances of the classes you import from there. [Import recipes](https://recipe-book.siraj.page/guides/import-recipes.md) walks through importing a recipe from a page. Paste a page's HTML source or JSON-LD into the [playground](https://recipe-book.siraj.page/playground/) to see what [`fromJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonld) reads from it and what [`toJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld) writes back. In a React app, replace `@recipe-book/core` with `@recipe-book/react/core` in this page's imports, so `@recipe-book/core/schema-org` becomes `@recipe-book/react/core/schema-org`.

## `findRecipeJsonLd`

```ts
function findRecipeJsonLd(html: string): Record<string, unknown>[]
```

Finds the schema.org Recipe nodes in a page's `<script type="application/ld+json">` tags.

| Name   | Type     | Default  | Description                                       |
| ------ | -------- | -------- | ------------------------------------------------- |
| `html` | `string` | Required | The page's HTML, such as `await response.text()`. |

Returns every node whose `@type` is `Recipe`, or a list that includes it, taken out of arrays, `@graph`, and another node's `mainEntity`, up to 32 levels deep. They're in document order, except that Recipes in a node's `@graph` come before those in its `mainEntity`, whichever key comes first. The type can also be written in full, with a prefix, or in any case, as in `'https://schema.org/Recipe'`, `'schema:Recipe'`, or `'recipe'`. It returns `[]` when the page has none, and a Recipe node with the `@id` of an earlier one only once, where the first appears. When the first holds nothing but keywords, as in a `mainEntity` of `{ "@type": "Recipe", "@id": "#recipe" }`, the later node is returned in its place. An empty `@id` counts as none, so it doesn't merge two recipes. Each node is a copy of the parsed JSON, as the page wrote it, except that an `author` or image that is an `@id` reference to a node at the top level of the JSON-LD, or reached from there through arrays and `@graph`, holds that node instead of the reference, an object with only that node's `@id`. That applies to the recipe's `author` and `image` and each step's `image` in `recipeInstructions`, including steps in sections and `ItemList`s. It lets [`fromJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonld) read the images that a Yoast or WP Recipe Maker page gives by reference, and keep the author's node, such as a `Person` with its `name`, in `extra`. A node fills one `author` slot and one image slot per call, the first of each in the order the recipes are returned, and in document order within one, except that a recipe's `image` comes before its steps', and within `recipeInstructions`, the images in a node's `itemListElement`, then in its `item`, come before the node's own `image`. That applies to a node of any type there, including an `ItemList` that `recipeInstructions` holds alone or in an array. Once a node fills a slot, later references to it in a slot of the same kind, in the same recipe or another, stay as they are, so the output grows in step with the page, and `fromJsonLd` ignores such an image with a warning. A reference to a node in any other field, such as an `Organization`'s `logo` or an `ImageObject` in a `WebPage`'s `mainEntity`, isn't followed. Other references, such as `mainEntityOfPage`, references inside the node an author or image holds, and references to the Recipe itself stay as they are.

When the page has no Recipe in those places, it also reads each `ItemList`'s `itemListElement`, where a roundup page lists its recipes, and returns each Recipe there, or in a `ListItem`'s `item`, in the same order, with a list's `itemListElement` read after its `@graph` and `mainEntity`. A list is read at the top level of the JSON-LD, in arrays and `@graph`, or as a node's `mainEntity`, but not inside a `ListItem` or another list. A `ListItem` whose `item` is missing, a URL, or an `@id` reference is skipped: when it links to the recipe's own page, fetch that page and find its recipe there. A page with a Recipe in those places gives only that, so a list of related recipes beside it isn't returned.

Besides these, no field is searched for Recipes. A Recipe inside another Recipe isn't returned, and a `mainEntity` node, on its own or in arrays at any depth, that is neither a Recipe nor an `ItemList` is skipped, with everything in it.

A tag inside an HTML comment is skipped, but a `<!--` in an attribute value or in a `<style>` or `<textarea>` element is text. So is one in a `<title>`, `<xmp>`, `<iframe>`, `<noembed>`, or `<noframes>` element, and everything after a `<plaintext>` tag, as in a browser outside `<svg>`, `<math>`, and `<noscript>`. A CDATA section, `<!x …>`, `<?x …?>`, or `</` followed by anything but an ASCII letter, such as `</ x>`, is a comment that ends at the next `>`. A quote starts an attribute value only right after `=` and any whitespace, so a stray quote, as in `content="Bake in a 9" pan."`, doesn't hide the tags after it. A tag runs past a `<` to its `>`, so in `<div <script …>` or `</p <script …>`, the script tag is part of the other tag and isn't read. `findRecipeJsonLd` ends a script's content at `</script` followed by a tab, line feed, form feed, carriage return, space, `/`, or `>`, as in `</script <x>`. As in a browser, after a `<!--` in a script's content, a `<script` followed by one of those characters makes the next such `</script` part of the content, unless a `-->` comes first. So `<script><!--document.write("<script>")</script>` hasn't ended, and a recipe script tag after it is part of it. The other elements above whose content is text end the same way at their own end tags, as in `</style/x>`, without that exception. [`fromJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonld)'s tag stripping in field text doesn't make that exception either: it ends a script at the first such `</script`, as described under [Fields it reads](https://recipe-book.siraj.page/reference/core/schema-org.md#fields-it-reads). A `type=` inside another attribute's value, as in `data-x="a type=application/ld+json"`, isn't the tag's `type`. A `type` written right after a quoted value, as in `id="x"type="application/ld+json"`, is read. Inside a tag, only a tab, line feed, form feed, carriage return, or space is whitespace, as in a browser, and any other character, including a no-break space, is part of the name or value it's in, so a script tag with a no-break space right after `<script`, or next to its only `type` or that `type`'s `=`, isn't read. A quote after any `=` starts a quoted value, even where a browser reads it as part of a name or an unquoted value, so a script tag right after `<div title=a="x>` isn't read, where a browser ends that tag at the `>`. As in a browser, the `/` and `+` in a tag's `type` can be character references, as in `type="application&#x2F;ld&#x2B;json"`, which templates that escape attribute values write. `&sol;` and `&plus;` stand for `/` and `+` only in lowercase, so `<script type="application&SOL;ld&PLUS;json">` isn't read. Only a tag's first `type` attribute counts. ASCII whitespace before its value is ignored, but whitespace there written as a character reference, such as `&#x20;`, isn't. Anything after `json` that starts with a character other than an ASCII letter, digit, or `_` is ignored, as in `type="application/ld+json; charset=utf-8"`.

A `<!--` or `<![CDATA[` that starts a tag's text, a `-->` or `]]>` that ends it, each of which can follow `//`, and then a `;` that ends what's left are left out before its JSON is parsed, as real pages have them. So `<!--{…}-->;` keeps its `-->` and is skipped. A tag whose JSON still doesn't parse is retried with the raw line breaks and tabs inside its strings escaped and a comma before a `]` or `}` left out, and skipped if it still doesn't.

```ts
import { findRecipeJsonLd, fromJsonLd } from '@recipe-book/core/schema-org'

const response = await fetch('https://example.com/pancakes')
const [node] = findRecipeJsonLd(await response.text())
const result = fromJsonLd(node)
```

Throws a [`RecipeBookError`](https://recipe-book.siraj.page/reference/core/errors.md#recipebookerror) with the code [`invalid_argument`](https://recipe-book.siraj.page/errors/invalid_argument.md) when `html` isn't a string.

## `fromJsonLd`

```ts
function fromJsonLd(input: unknown): FromJsonLdResult
function fromJsonLd(
  input: unknown,
  options?: FromJsonLdOptions,
): FromJsonLdResult
```

Reads a schema.org Recipe from JSON-LD into a [`Recipe`](https://recipe-book.siraj.page/reference/core/types.md#recipe).

| Name      | Type                                                                                                 | Default  | Description                                                                                                                                                                                                                                                  |
| --------- | ---------------------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `input`   | `unknown`                                                                                            | Required | A Recipe node, or an array, `@graph`, `mainEntity`, or `ItemList` that holds one up to 32 levels deep, such as a node from [`findRecipeJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#findrecipejsonld) or a script tag's parsed JSON. |
| `options` | [`FromJsonLdOptions`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonldoptions) | `{}`     | The decimal mark and the cup and tablespoon the page's text uses. It's ignored when it's a number or another value that isn't an object, so `nodes.map(fromJsonLd)` works; a string throws.                                                                  |

Returns a [`FromJsonLdResult`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonldresult). Issue paths point into the JSON-LD, such as `recipeIngredient[3]`.

```ts
import { fromJsonLd } from '@recipe-book/core/schema-org'

const result = fromJsonLd({
  '@context': 'https://schema.org',
  '@type': 'Recipe',
  name: 'Buttermilk pancakes',
  author: { '@type': 'Person', name: 'Ada' },
  recipeYield: ['4', '4 servings'],
  recipeIngredient: ['1 &frac12; cups (190 g) all-purpose flour', '2 eggs'],
  recipeInstructions: [
    { '@type': 'HowToStep', text: 'Whisk the flour and eggs.' },
    { '@type': 'HowToStep', text: 'Cook on a hot griddle.' },
  ],
})

result.success && result.data.servings // { amount: 4 }
result.success && result.data.ingredients[0]?.items[0] // { id: 'all-purpose-flour', name: 'all-purpose flour', quantity: { amount: 1.5, unit: 'cup' }, equivalents: [{ amount: 190, unit: 'g' }], optional: false }
result.extra // { author: { '@type': 'Person', name: 'Ada' } }
```

Pass `options` when the page writes comma decimals, or metric cups or Australian tablespoons, as [`ParseQuantityOptions`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantityoptions) describes. Neither option is read from `inLanguage` or from the site's language:

```ts
import { fromJsonLd } from '@recipe-book/core/schema-org'

const result = fromJsonLd(
  {
    '@type': 'Recipe',
    name: 'Brot',
    recipeYield: '1,500 g',
    recipeIngredient: ['1,500 kg Mehl', '0,5 l Wasser'],
    recipeInstructions: ['Backen.'],
  },
  { decimal: ',' },
)

result.success && result.data.yield // { amount: 1.5, unit: 'g' }
result.success && result.data.ingredients[0]?.items[0]?.quantity // { amount: 1.5, unit: 'kg' }
```

Without `decimal: ','`, the yield is ignored and the first ingredient is named `'1,500 kg Mehl'` with no quantity. Each gets an [`invalid_quantity`](https://recipe-book.siraj.page/errors.md#issue-invalid_quantity) warning whose message gives both readings of `1,500`. An error thrown by a getter or proxy in the input or options passes through.

Doesn't throw for bad input. An error thrown by a getter or a proxy in the input passes through. An array that holds itself, which a program can build but `JSON.parse` can't, is read once: where it repeats, it counts as nested more than 32 levels deep. The result fails only when there's no Recipe node, or the recipe's name is missing, isn't text, or is only whitespace once its markup is removed and its entities decoded, such as `''`, `'<p>&nbsp;</p>'`, or `'<style>p {}</style>'`. Then `error` is a [`RecipeValidationError`](https://recipe-book.siraj.page/reference/core/errors.md#recipevalidationerror) with the code [`invalid_recipe`](https://recipe-book.siraj.page/errors/invalid_recipe.md), and the failing issue is an [`invalid_type`](https://recipe-book.siraj.page/errors.md#issue-invalid_type) error at `(root)` or a [`missing_field`](https://recipe-book.siraj.page/errors.md#issue-missing_field) or `invalid_type` error at `name`. It throws a [`RecipeBookError`](https://recipe-book.siraj.page/reference/core/errors.md#recipebookerror) with the code [`invalid_argument`](https://recipe-book.siraj.page/errors/invalid_argument.md) for an invalid option, as [`parseQuantity`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantity) does, naming `fromJsonLd`.

### Fields it reads

| schema.org                          | Recipe                                    | How it's read                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| ----------------------------------- | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`                              | `name`                                    | As text. It's required.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| `description`                       | `description`                             | As text.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `image`                             | `image`                                   | A URL, an `ImageObject`'s `url` or `contentUrl`, or an `@id` reference to a node at the top level of the JSON-LD, or reached from there through arrays and `@graph`, read the same way. From a list, the first URL the recipe can hold is kept, or, when it's a resized copy, `a-225x225.jpg`, a later `a.jpg` as text, and nothing else after it is read. Each URL before it with a scheme other than http or https, such as a `data:` URL, or that the URL parser rejects, such as `http://[bad`, gets an [`invalid_url`](https://recipe-book.siraj.page/errors.md#issue-invalid_url) warning at its own path, such as `image[0]`, ending "It is ignored." If none can be held, there's no image. A reference to the Recipe itself is ignored, with an [`invalid_type`](https://recipe-book.siraj.page/errors.md#issue-invalid_type) warning. A node that several images reference gives its warnings once, at its own path. One object that several images hold gives them once, under the first image that holds it. Near the 32-level limit, where how deep the object is decides where it's cut off, it's read again at each depth, under the first image that holds it there. Its values within the limit give their warnings again, and each value past it gets an `invalid_type` warning instead.                                                                                                                                                                                                                                                                                                                                                                                                     |
| `recipeYield`                       | `servings`, `yield`                       | A number, or text such as `'Serves - 4'` or `'8 - 10 serving(s)'`, is servings, as is text whose last word outside parentheses is `serves` or a servings word, as in `'4 serves'` or `'4 generous servings'`. Servings words are `serving`, `portion`, and `person`, singular or plural, and `people`. Before text is read, a leading `makes`, `serves`, `serving`, `servings`, `yield`, or `yields`, in any case and with or without a colon, hyphen, en dash, or em dash after it, is dropped, and then a leading `about`, so `'Makes 4'` is 4 servings. Text that isn't servings is the yield, as [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe) reads what's left of it, so `'Makes about 24 cookies'` yields 24 cookies. Text with commas, such as `'4 servings, 24 cookies'`, is a list of values. The yield is the first value with an amount, so `'One 9-inch pie, 8 slices'` yields 8 slices, and a value without one gets an [`invalid_quantity`](https://recipe-book.siraj.page/errors.md#issue-invalid_quantity) warning. An amount of "a" or "an", as in `'a few'`, is 1, but one whose amount is a number comes first, so `['a few', '24 cookies']` yields 24 cookies. A `QuantitativeValue` is servings without a `unitText` or with a servings word, and the yield with any other. Its amount is `value`, or `minValue` to `maxValue`. A bare number equal to the yield's amount, as in `['28', '28-32 cookies']`, counts the yield. Of several numbers of servings, the first with a servings word, such as `'6 servings'`, is kept, even after `'4'`. Without one, a range with a bare first number is kept, as in `['6', '6-8']`, or else the first. |
| `prepTime`, `cookTime`, `totalTime` | `times.prep`, `times.cook`, `times.total` | An ISO 8601 duration, in minutes. A JSON-LD value object, such as `{ '@type': 'Duration', '@value': 'PT30M' }`, is read for its `@value`. Three slips are read as meant: a unit with no number, as in `'PTH5M'`, days after the `T`, as in `'PT0D30M'`, and hours or seconds with no `T`, as in `'P1H'`. A zero time, such as `'PT0S'`, is left out. A number of minutes, such as `30`, isn't a duration, and a time longer than `Number.MAX_SAFE_INTEGER` minutes is too long to hold, so each is left out with an [`invalid_duration`](https://recipe-book.siraj.page/errors.md#issue-invalid_duration) warning. Years and months aren't accepted, because their length varies, unless they're zero, as in `'P0Y0M0DT0H30M'`, so a duration with a nonzero year or month is left out with that warning too. `'P30M'` is 30 months, not 30 minutes. From a list, such as `['PT30M']`, the first time that isn't left out is read, and each later one that isn't left out gets an [`ignored_value`](https://recipe-book.siraj.page/errors.md#issue-ignored_value) warning. A warning for an item in a list is at its own path, such as `prepTime[1]`, and an empty list is left out without a warning.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| `recipeIngredient`                  | `ingredients`, `system`                   | [`parseIngredientLine`](https://recipe-book.siraj.page/reference/core/parsing.md#parseingredientline) reads each line. A `PropertyValue` is read as the line its `value`, `unitText`, and `name` make, such as `'2 cups flour'`. Its `text`, or that of another object such as a `HowToSupply`, stands in for a `name` that's missing or blank, and an object that makes no line, such as one whose `text` is only whitespace, is left out with an [`invalid_type`](https://recipe-book.siraj.page/errors.md#issue-invalid_type) warning. An `<a>` tag in a line can give the ingredient its `url`, as described below. A line outside a named section that reads as a heading titles a section of the lines after it, up to the next heading or named section. A heading has a letter but no number or quantity, and it ends in a colon, starts with "For the" without a comma or colon, starts with "TO" in capitals, or starts with one or more `#` and a space, as in `'For the sauce:'`, `'TO SERVE'`, and `'## Sauce'`. Each run of whitespace in a line, such as a tab or a no-break space, reads as one space, and whitespace at either end is ignored, so `'#&nbsp;Sauce'` and a `'# Sauce'` indented with a tab are headings too. A heading on the last line, or followed by another heading or a named section, stays an ingredient. schema.org has no field for the measurement system, so `system` is inferred from the ingredients' quantities, as [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe) infers it.                                                                                                                                              |
| `recipeInstructions`                | `steps`                                   | Text, with one step per line, or a list of text, `HowToStep`, `HowToSection`, and `ListItem` items. A line that's only a step's label, such as `'Step 2'`, isn't a step, and a line can be split into steps, as described after this table. A `HowToTip` is read as a step. A step's `text` can be a list of text, joined with commas, or with a space after one that ends in `.`, `!`, `?`, `:`, `;`, or `,`, so `['Rinse the leeks', 'pat them dry.', 'Slice them.']` reads as `'Rinse the leeks, pat them dry. Slice them.'`. A step's `name` is kept only when it adds to its `text`, unlike `'Step 1'` or the text's first words. A name that's only a step's number, such as `'1.'`, is dropped too. A step without text uses its `name` as its text, and a step with neither, such as one with only an image, is left out with a [`missing_field`](https://recipe-book.siraj.page/errors.md#issue-missing_field) warning.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| `tool`                              | `equipment`                               | Text, or a `HowToTool` with a `name`, a `requiredQuantity`, and a `url`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `nutrition`                         | `nutrition`                               | `servingSize` and the `NutritionInformation` quantities, such as `calories` and `fatContent`, read as [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe) reads [nutrition](https://recipe-book.siraj.page/reference/core/types.md#nutrition), except that words can follow an amount, up to the first character that isn't a letter, a space, or a hyphen between letters. So `fatContent: '25 grams fat'` and `'5 g fat (2 g saturated fat)'` read as `fat: 25` and `fat: 5`, and `sodiumContent: '0.2 grams of sodium'` as `sodium: 200`. The first word is the unit unless it names the field's own nutrient and isn't a unit, as in `fatContent: '25 fat'`. Any later word that names no nutrient is read through, as `added` is in `sugarContent: '10 g added sugars'`, read as `sugar: 10`. An amount followed by a word that begins like the name of another nutrient or of salt is left out, with a warning, such as `protein`, `carbs`, `sat`, `monounsaturated`, or `poly-unsaturates` in `fatContent`, `salt` in `sodiumContent`, or the `alcohols` of sugar alcohols in `sugarContent`. So is one whose first nutrient word doesn't begin the field's name, such as `'5 g fat'` in `saturatedFatContent`, `transFatContent`, and `unsaturatedFatContent`.                                                                                                                                                                                                                                                                                                                                                                                                       |
| Any other field                     | `extra`                                   | As it was. `@context` and `@type` aren't kept. A field with a value nested more than 32 levels deep is left out with an [`invalid_type`](https://recipe-book.siraj.page/errors.md#issue-invalid_type) warning, so `extra` stays safe to serialize. The levels count from the top of `input`, not from the Recipe node, so for a node at `@graph[0]`, `@graph` and `0` are two of them.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |

A field written in another case, such as `PrepTime` or `RecipeInstructions`, is read when the field itself has no value, and so is the deprecated `ingredients` in place of `recipeIngredient`. Its issues are at the key the page uses, such as `ingredients[2]`, and it isn't kept in `extra`. When the field has a value, the other key is kept in `extra`, as it was.

In `recipeIngredient` and `recipeInstructions`, a named `HowToSection` or `ItemList` is a titled section, except inside another named one, where its items join that section and its name is dropped. It's a section even when it has `text`, and as from [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe), its `text` is left out with an [`unknown_field`](https://recipe-book.siraj.page/errors.md#issue-unknown_field) warning, because a section holds only a title and items. A `text` that's empty, `null`, or only whitespace is left out without one, but one that's only markup, such as `'<p>&nbsp;</p>'`, still gets it. A `HowToSection` or `ItemList` without an `itemListElement` key is read as a `HowToStep` with the same fields would be, so in `recipeIngredient` its `name` or `text` can be a heading, and one with neither is left out. A `ListItem` is read as its `item`, which can also be a list or a section, and one with no `item`, or with empty text or an empty list as its `item`, is read by its `name`. When every item in a list has a numeric `position`, as `ListItem`s do, the items are read in that order. Otherwise they're read in document order. The items of an unnamed `HowToSection` or `ItemList` take its place in the list around it. One with `text` and an `itemListElement` is read the same way, and its `text` is left out with the same `unknown_field` warning, or without one when it's empty, `null`, or only whitespace. A section's `itemListElement` and `name` are also read when they're written `ItemListElement` and `Name`. An item nested more than 32 levels deep, counting from the top of `input`, is left out with an [`invalid_type`](https://recipe-book.siraj.page/errors.md#issue-invalid_type) warning.

In `recipeInstructions` text, one step per line has two exceptions. A line that's only a step's label, such as `'3.'`, `'Step 2'`, or `'Stap 1:'`, isn't a step. A label's word can be `step`, `stap`, `schritt`, `étape` or `etape`, `passo`, or `instruction`, in any case. And a line where one sentence runs into the next with no space, as in `'Mix it.Bake it.'`, is split there into two steps, while a `HowToStep`'s `text` gets a space there instead. Sentences run together where two letters, the second lowercase, and then `.`, `!`, `?`, `)`, `.)`, `!)`, or `?)` come right before an uppercase letter. So `'e.g.add'` and `'site.com'` aren't split, and nor are `'z.B.'` and `'a)Butter'`, where a letter stands on its own. A step's number at its start is left out when it's one or two digits, a period, and a space, as in `'2. Mix.'`, but not in `'2) Mix.'`.

A `HowToTool`'s `requiredQuantity` that's a `QuantitativeValue` is read as its `value`.

An image URL in `image` or a step's `image`, whether it's text or in an `ImageObject`, is left out with an [`invalid_type`](https://recipe-book.siraj.page/errors.md#issue-invalid_type) warning when it's nested more than 32 levels deep, counting from the top of `input`. One that's longer than 4,096 UTF-16 code units, after the cleaning below, is left out with an [`invalid_url`](https://recipe-book.siraj.page/errors.md#issue-invalid_url) warning that gives its length, such as `Expected a URL of at most 4096 UTF-16 code units, received 5000. It is ignored.`, when the URL parser reads it as http, https, or relative. Otherwise it gets the warning a shorter one would, such as `received "data:…".` In each case, the next URL is read. An image with no URL to read, such as an `ImageObject` with neither `url` nor `contentUrl` or an `@id` that matches no node, gets an `invalid_type` warning such as `Expected an image URL, an ImageObject with a url, or a list of them, received an object. It is ignored.` In a list, such an image gets no warning of its own. The list gets that warning, ending `received an array. It is ignored.`, only when it keeps no image and none of its images got another warning, so `[{ '@type': 'ImageObject' }, 'data:…']` gives only the `invalid_url`.

Every string has its comments and tags removed first, along with the content of `<script>` and `<style>` elements. A `>` inside an attribute value quoted right after `=` and any whitespace doesn't end a tag, but a `<` that starts a tag ends the quoted value, so the cleaner misreads some valid markup: `<img alt="a <b">rest` becomes `<img alt="a rest`, not `rest`. Removing a tag can form a new one, which the next pass removes, for up to 8 passes. So `x<scr<b></b>ipt>rest` becomes `x`: the `<script>` that forms has no end tag, so it takes the rest of the string. A `<` that could still start a tag, with a `>` after it, is removed, but text such as `x<y` keeps its `<`. Then its character references are decoded, such as `&frac12;` to `½` and `&amp;` to `&`, so an encoded tag such as `&lt;b&gt;` stays as the text `<b>`. A reference encoded twice, as a page that encodes its JSON-LD twice writes it, is decoded too, so `&amp;auml;` becomes `ä` and `&amp;amp;` becomes `&`. `&amp;lt;` and `&amp;gt;` are decoded once, so `&amp;lt;b&amp;gt;` stays as the text `&lt;b&gt;`. `&circ;`, `&tilde;`, and HTML 4.01's names for Greek letters and for characters from U+2100 on, such as `&alpha;`, `&rarr;`, and `&le;`, are kept as written, except `&trade;` and `&minus;`. HTML 4.01's other names are decoded, and so are HTML5's names for Latin Extended-A letters, such as `&lstrok;` and `&gbreve;`, but most other HTML5 names, such as `&check;`, are kept as written. A numeric reference from `&#128;` to `&#159;`, in decimal or hex, such as `&#x93;`, is read as the windows-1252 character a browser shows for it, so `&#150;` is an en dash, except the five that windows-1252 leaves unassigned, such as `&#129;`, which stay their code points. `<br>`, `<p>`, `<li>`, `<div>`, and heading tags end a line. Inside a tag, only a tab, line feed, form feed, carriage return, or space is whitespace, as in a browser, and any other character, including a no-break space, is part of the name or value it's in: a `<br>` with a no-break space before its `/` doesn't end a line, and a `<style>` with one before its `>` isn't a style element, so its text is kept. A `<script>` or `<style>` element ends at the first `</script` or `</style`, in any case, that matches it and is followed by a tab, line feed, form feed, carriage return, space, `/`, or `>`, so `</style x>` and `</SCRIPT>` end one, but `</styles>` and `</style`, a no-break space, and `>` don't. The end tag is then removed as any tag is, so one with a `<` before its `>` stays as text: `a<style>x</style x<b>Mix well.` becomes `a</style xMix well.`. A quote after any `=` starts a quoted value, even where a browser reads it as part of a name or an unquoted value: the cleaner removes `<i title=a="b>c">` as one tag, and likewise `<i`, a no-break space, and `title="a>b">`, where a browser ends each tag at the first `>` and shows `c">` or `b">`.

An `<a>` tag in an ingredient line gives the ingredient its `url`: the `href` of the first one that is http, https, or relative, such as `'https://shop.example.com/flour'` in `'3 cups <a href="https://shop.example.com/flour">flour</a>'`. The line's text reads as it would without the link. Only a tag in the markup as written is read, so a tag in a comment, an encoded `&lt;a&gt;`, or one that forms only after another tag is removed isn't a link. The tag's name is `a`, in any case, followed by a tab, line feed, form feed, carriage return, space, `/`, or `>`, so `<abbr>` and `</a>` aren't links. Its attributes are read as a browser reads them, and the first one named `href` gives the link, so `data-href`, or `href=` inside another attribute's value, isn't read. A quoted value that isn't closed gives no link. The value is decoded as the rest of the line is and trimmed, but not resolved, so a relative link is relative to the page the recipe came from, and `url` is ready for a DOM property or a JSX attribute such as `href={url}`, but needs escaping to go into HTML source. [Import recipes](https://recipe-book.siraj.page/guides/import-recipes.md#resolve-ingredient-links) shows how to resolve it.

A link to a place on the same page (`#…`) or an empty one is left out without a warning. A link with another scheme, such as `javascript:`, or that the URL parser rejects, such as `http://[bad`, is left out with an [`invalid_url`](https://recipe-book.siraj.page/errors.md#issue-invalid_url) warning at the line's path, such as `recipeIngredient[3]`, and the ingredient is still read. Each further, different link in the line is an `ignored_value` warning at the same path that names the link that gives the `url` and the ignored one. Every line of a string reports at the string's path, which never gets the same link warning twice, so two `javascript:` links in one string give one `invalid_url`. When the links change how the rest of a string reads, as in `<<a href="/flour">b>flour`, no line of that string has a link. As with text, a link inside markup the cleaner misreads, such as in a `<textarea>` or in another tag's quoted attribute value, is read too, unless removing it forms a tag around it, as in `<span title="<a href="/q">">flour`. A link in a section's title isn't read.

### Values it leaves out

Reading is forgiving, because you can't fix another site's markup. A value the recipe can't hold is left out, with a warning at its JSON-LD path. Its message ends "It is ignored.", but its [issue code](https://recipe-book.siraj.page/errors.md#issue-codes) isn't always the one [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe) would report: a `HowToSupply` in `recipeIngredient` whose `name` and `text` are blank is `invalid_type`, where `parseRecipe` reports `missing_field` for an ingredient with no name. Like `null` and empty text, an empty list is left out without a warning: as an `image`, a step's `image`, or `nutrition`, in a list of yields or times, and in a list of images, ingredients, or steps, even one at the depth where text would be nested too deep to read. One nested deeper than that is `invalid_type`, as text nested too deep is. In a list of images, a number or another value with no URL to read is left out without a warning too, unless it's nested too deep to read, and nothing after the image that's kept gives a warning. A list of images that keeps no image and gives no other warning, such as `[null]`, `[[]]`, or `[5]`, is `invalid_type`. A value of the wrong type, such as a number in `recipeIngredient`, is `invalid_type`. An amount that can't be held is [`invalid_amount`](https://recipe-book.siraj.page/errors.md#issue-invalid_amount), such as a `requiredQuantity` of `0`, or [`invalid_range`](https://recipe-book.siraj.page/errors.md#issue-invalid_range), such as a yield of `'10-8 cookies'`. A `nutrition` field that isn't in [`SchemaOrgNutritionInformation`](https://recipe-book.siraj.page/reference/core/schema-org.md#schemaorgnutritioninformation), such as `vitaminCContent`, is [`unknown_field`](https://recipe-book.siraj.page/errors.md#issue-unknown_field) when it has a value, and a `data:` image or a `javascript:` link in an ingredient line is `invalid_url`. A recipe with no ingredients or no steps, including when every one was left out, or a titled section with none, gets an [`empty_list`](https://recipe-book.siraj.page/errors.md#issue-empty_list) warning, as from `parseRecipe`. A second Recipe node, another number of servings with a different amount, a second yield, a second duration in a time's list, or a second, different link in an ingredient line is an [`ignored_value`](https://recipe-book.siraj.page/errors.md#issue-ignored_value) warning that names the value that was kept. A Recipe node with the `@id` of an earlier one is the same recipe, not a second one, and which copy is read follows the same rules as in [`findRecipeJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#findrecipejsonld). This input gets two warnings:

```ts {7-8}
import { fromJsonLd } from '@recipe-book/core/schema-org'

const result = fromJsonLd({
  '@context': 'https://schema.org',
  '@type': 'Recipe',
  name: 'Toast',
  image: 'data:image/png;base64,iVBORw0KGgo=',
  recipeYield: ['4', '2 loaves', '1 pan'],
  recipeIngredient: ['2 slices bread'],
  recipeInstructions: ['Toast the bread.'],
})
```

result.warnings
```json title="result.warnings"
[
  {
    "code": "invalid_url",
    "severity": "warning",
    "path": ["image"],
    "message": "Expected an http or https URL, or a relative one, received \"data:…\". It is ignored."
  },
  {
    "code": "ignored_value",
    "severity": "warning",
    "path": ["recipeYield", 2],
    "message": "Only one yield is read, \"2 loaves\", so this one is ignored."
  }
]
```

Other `ignored_value` warnings:

| JSON-LD                                     | Path             | Message                                                             |
| ------------------------------------------- | ---------------- | ------------------------------------------------------------------- |
| Two Recipe nodes, the first named `'Toast'` | `(root)`         | `Found 2 recipes. Only the first, "Toast", is read.`                |
| `recipeYield: ['4', '6']`                   | `recipeYield[1]` | `Only one number of servings is read, "4", so this one is ignored.` |
| `prepTime: ['PT30M', 'PT1H']`               | `prepTime[1]`    | `Only one duration is read, "PT30M", so this one is ignored.`       |

## `toJsonLd`

```ts
function toJsonLd(recipe: Recipe, options?: ToJsonLdOptions): ToJsonLdResult
```

Writes a recipe as schema.org Recipe JSON-LD for search engines' recipe results.

| Name      | Type                                                                                             | Default  | Description                                                                                                                                                                                    |
| --------- | ------------------------------------------------------------------------------------------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `recipe`  | [`Recipe`](https://recipe-book.siraj.page/reference/core/types.md#recipe)                        | Required | A recipe from [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe) or [`fromJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonld). |
| `options` | [`ToJsonLdOptions`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonldoptions) | `{}`     | The servings and measurement system to write, the page's URL, and fields to add.                                                                                                               |

Returns a [`ToJsonLdResult`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonldresult): `data`, the JSON-LD, which is plain JSON when `extra` is, and `warnings`, the issues listed below.

```ts
import { parseRecipe } from '@recipe-book/core'
import { toJsonLd } from '@recipe-book/core/schema-org'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  servings: 4,
  times: { prep: 10, cook: 15 },
  ingredients: [
    { name: 'all-purpose flour', quantity: '1 ½ cups', equivalents: ['190 g'] },
    { name: 'egg', plural: 'eggs', quantity: 2 },
    {
      name: 'butter',
      quantity: '3 tbsp',
      note: 'melted',
      equivalents: ['42 g'],
    },
  ],
  steps: [
    'Whisk the flour, eggs, and butter.',
    'Cook ¼-cup portions on a buttered griddle, 2–3 minutes per side.',
    { title: 'To serve', items: ['Stack three pancakes on each plate.'] },
  ],
  nutrition: { servingSize: '3 pancakes', calories: 250, fat: 9 },
})
if (!result.success) throw result.error

const { data, warnings } = toJsonLd(result.data, {
  url: 'https://example.com/pancakes',
  extra: { author: { '@type': 'Person', name: 'Ada' } },
})

warnings // [{ code: 'missing_field', severity: 'warning', path: ['image'], message: 'Add an image. Google requires one for recipe results.' }]
```

data
```json title="data"
{
  "@context": "https://schema.org",
  "@type": "Recipe",
  "name": "Buttermilk pancakes",
  "recipeYield": ["4", "4 servings"],
  "prepTime": "PT10M",
  "cookTime": "PT15M",
  "recipeIngredient": [
    "1 ½ cups (190 g) all-purpose flour",
    "2 eggs",
    "3 tbsp (42 g) butter, melted"
  ],
  "recipeInstructions": [
    {
      "@type": "HowToStep",
      "text": "Whisk the flour, eggs, and butter.",
      "url": "https://example.com/pancakes#step-1"
    },
    {
      "@type": "HowToStep",
      "text": "Cook ¼-cup portions on a buttered griddle, 2–3 minutes per side.",
      "url": "https://example.com/pancakes#step-2"
    },
    {
      "@type": "HowToSection",
      "name": "To serve",
      "itemListElement": [
        {
          "@type": "HowToStep",
          "text": "Stack three pancakes on each plate.",
          "url": "https://example.com/pancakes#step-3"
        }
      ]
    }
  ],
  "nutrition": {
    "@type": "NutritionInformation",
    "servingSize": "3 pancakes",
    "calories": "250 kcal",
    "fatContent": "9 g"
  },
  "author": {
    "@type": "Person",
    "name": "Ada"
  }
}
```

Give a recipe with nutrition its own `servings`, as these pancakes have, along with any yield, because nutrition is for one serving, and a yield such as 24 cookies doesn't say how many servings that is. With `servings: 24` and `yield: '24 cookies'` in the recipe, `recipeYield` is `['24', '24 servings', '24 cookies']`, and with the yield alone, it's `['24 cookies']`.

[`SchemaOrgRecipe`](https://recipe-book.siraj.page/reference/core/schema-org.md#schemaorgrecipe) lists each field `toJsonLd` writes. Each ingredient is one line that [`parseIngredientLine`](https://recipe-book.siraj.page/reference/core/parsing.md#parseingredientline) reads back, with its quantity at the servings and in the measurement system you chose. The ingredient's other quantities follow in parentheses: after the quantity for a measure, as in `'1 ½ cups (190 g) all-purpose flour'`, and after the name for a count, as in `'2 eggs (100 g)'`, so the weight is for both eggs. Several are separated by semicolons, as in `'1 cup (120 g; 4 oz) flour'`. After a count unit, as in `'3 packages (8 oz; 227 g each) cream cheese'`, they're for one each and end with `each` when every one, multiplied by the count as written, is within 2% of what it was. Otherwise they're the total and end with `total`, as in `'6 slices (5 oz; 142 g total) bacon'`, where ⅞ oz a slice would make 5 ¼ oz. A count of exactly 1 has neither, as in `'1 can (28 oz) crushed tomatoes'`. So a quantity written for one each can read back up to 2% off: 680 g in 3 packages is written as 227 g each and reads back as 681 g. The note follows a comma, and an optional ingredient ends `' (optional)'`, even when its note or name already says so: `{ name: 'sugar', note: '(optional)', optional: true }` is written as `'sugar, (optional) (optional)'`, which reads back without the note. Spaces are plain spaces, unlike the no-break spaces of [`formatIngredient`](https://recipe-book.siraj.page/reference/core/formatting.md#formatingredient).

As [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe) reads them, a `description`, `image`, step `name`, step `image`, or `nutrition` value that's empty or only whitespace isn't written, nor is a `nutrition` of `null`, `0`, or `false` in a recipe built by hand, and a section of steps whose `title` is empty or only whitespace is written as its steps, without a `HowToSection`. Other text isn't trimmed. So a recipe whose `image` is empty or only whitespace gets the `image` warning, unless `extra` has an `image`, which is written in its place.

Google requires absolute image URLs, so when `url` is an absolute URL, a relative `image`, the recipe's, a step's, or one from `extra`, is resolved against it, as a link on that page would be. With `url: 'https://example.com/recipes/toast?servings=2#method'`, `'toast.jpg'` becomes `'https://example.com/recipes/toast.jpg'`, `'../toast.jpg'` becomes `'https://example.com/toast.jpg'`, `'/images/toast.jpg'` becomes `'https://example.com/images/toast.jpg'`, and `'//cdn.example.com/toast.jpg'` becomes `'https://cdn.example.com/toast.jpg'`. Some images are written as they are: one with a scheme, such as `https:` or `data:`, one that doesn't resolve, an `image` in `extra` that is blank or isn't a string, and every image when `url` is missing or isn't an absolute URL, such as `'/recipes/toast'`.

schema.org has no place for ingredient section titles, the recipe's notes, custom times, or equipment beyond its name, so they aren't written, and ingredient lines are written as plain text, without their `url`. Reading `data` back with [`fromJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonld) gives a similar recipe, not the same one. Ids are derived from names, and each yield unit is in the form the text used. Expect changes such as these:

- Quantities are kitchen-rounded, so 6.7 oz comes back as 6 ⅔ oz.
- A quantity that isn't in the measurement system `toJsonLd` writes swaps places with its equivalent or its conversion.
- A comma or a parenthetical in an ingredient's name becomes a note, as in `'tomatoes, diced'` and `'tomatoes (canned)'`. A comma between two digits stays in the name, so `'tart shell 9,5 inch'` comes back whole.
- A note after a name that ends in `boneless` or `skinless`, or that leaves a parenthesis open, becomes part of the name, because the comma before the note doesn't end a name there, unless the note is only preparation words from the Note row of [`parseIngredientLine`'s parts](https://recipe-book.siraj.page/reference/core/parsing.md#parseingredientline), such as `'diced'` or `'peeled and diced'`. After `boneless` or `skinless`, a note also stays one when it starts with a preparation word from that row's dash list, as `'cubed small'` does, or with only preparation words and a comma, as `'room temperature, for grilling'` does. So 1 lb `'boneless'` with the note `'skinless chicken thighs'` comes back as 1 lb `'boneless, skinless chicken thighs'`.
- A name that starts with a unit becomes the quantity's unit, so 2 `'cup of coffee'` comes back as 2 cups of `'coffee'`.
- A name that starts with a number can read as a quantity. Without a quantity, `'7 Up'` comes back as 7 `'Up'`, and the line `'00 flour, for dusting'` comes back whole as the name, with a warning. So does 2 `'00 flour'`, which loses its quantity. A unit between the amount and the name, as in 200 g `'00 flour'`, keeps the name.
- Without a quantity, a name or note that ends in a colon and a quantity can read that quantity as the ingredient's, so `'salt: 1 g'` comes back as 1 g of `'salt'`.
- An ingredient without a quantity whose line reads as a heading, such as `'For the sauce:'`, can come back as a section title, as [`recipeIngredient`](https://recipe-book.siraj.page/reference/core/schema-org.md#fields-it-reads) describes.
- A step's name is dropped when it repeats the start of its text or is only a step's label, such as `'Step 1'`.
- A step's number of one or two digits followed by a period and a space at the start of its text, as in `'2. Mix.'`, is dropped, though not one written as `'2) Mix.'`. A space is added where one sentence runs into the next, as in `'Mix.Bake.'`.
- A step's text, the name, and the description come back as one line of plain text, without line breaks or HTML, and with numeric character references, most of HTML 4.01's names, and HTML5's names for Latin Extended-A letters decoded. So `'Mac &amp; cheese'` comes back as `'Mac & cheese'`.
- A yield in a servings word, such as 6 portions, comes back as servings. With servings of its own, the recipe keeps those and loses the yield, with an `ignored_value` warning when the two numbers differ.
- In metric text, a `cup-metric` or `tbsp-au` quantity is written as cup or tbsp, as in `'1 cup caster sugar'`, so it comes back as the US unit unless you read it with the same [`units`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantityoptions). In `'us'` text, one in parentheses is written in mL instead, as in `'1 cup (250 mL) caster sugar'` and `'8 tsp (40 mL; 40 g) butter'`, and it's left out when the ingredient also has a quantity in mL, cL, dL, or L, as in `'4 ¼ cups (1 L) stock'`. Decimals are written with a period, so they need no `decimal`.

`warnings` has these issues. A `missing_field` path is a schema.org name, an `invalid_duration` path is in the recipe, and the path of an option it ignores is in `options`:

| Code               | Path                                      | When                                                                                                                                                                                                                                                                                                                 |
| ------------------ | ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `missing_field`    | `image`                                   | `data` has no `image`. Google requires one for recipe results.                                                                                                                                                                                                                                                       |
| `missing_field`    | `recipeYield`                             | `data` has `nutrition` but the recipe has no `servings`, even with a `yield`. Nutrition is for one serving, so `recipeYield` needs the number of servings. A `recipeYield` from [`extra`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonldoptions), written when the recipe has neither, counts. |
| `invalid_duration` | `times.prep`, `times.cook`, `times.total` | The time is longer than `Number.MAX_SAFE_INTEGER` minutes, or, in a recipe built by hand, is `NaN` or a value that `Number` makes `NaN`, such as `'abc'` or `{}`, so it's left out.                                                                                                                                  |
| `invalid_amount`   | `options.servings`                        | The `servings` option is a number outside a millionth to a million times the recipe's [scaling base](https://recipe-book.siraj.page/reference/core/resolving.md#resolverecipeoptions), such as `0` or `NaN`, so the recipe is written unscaled.                                                                      |
| `invalid_type`     | `options.servings`                        | The `servings` option isn't a number, so the recipe is written unscaled.                                                                                                                                                                                                                                             |
| `invalid_type`     | `options.system`                          | The `system` option isn't `'metric'` or `'us'`, so quantities are written in `recipe.system`, else `'metric'`.                                                                                                                                                                                                       |

To give an `ImageObject` or several images, such as the three aspect ratios Google recommends, or to replace any field `toJsonLd` writes, spread `data` into a new object rather than using [`extra`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonldoptions):

```ts {13-18}
import { parseRecipe } from '@recipe-book/core'
import { toJsonLd } from '@recipe-book/core/schema-org'

const result = parseRecipe({
  name: 'Toast',
  image: 'https://example.com/toast.jpg',
  ingredients: [{ name: 'bread', quantity: '2 slices' }],
  steps: ['Toast the bread.'],
})
if (!result.success) throw result.error

const jsonLd = {
  ...toJsonLd(result.data).data,
  image: [
    'https://example.com/toast-1x1.jpg',
    'https://example.com/toast-4x3.jpg',
    'https://example.com/toast-16x9.jpg',
  ],
}
```

In React, [`<Recipe.JsonLd>`](https://recipe-book.siraj.page/reference/react/json-ld.md) writes the script inside a [`<Recipe.Root>`](https://recipe-book.siraj.page/reference/react/root.md). To put `data` in a page yourself, serialize it with every `<` escaped as `\u003c`, so recipe text can't end the script tag:

app/toast/page.tsx
```tsx title="app/toast/page.tsx" {18}
import { parseRecipe } from '@recipe-book/core'
import { toJsonLd } from '@recipe-book/core/schema-org'

const result = parseRecipe({
  name: 'Toast',
  image: 'https://example.com/toast.jpg',
  ingredients: [{ name: 'bread', quantity: '2 slices' }],
  steps: ['Toast the bread.'],
})
if (!result.success) throw result.error
const { data } = toJsonLd(result.data, { url: 'https://example.com/toast' })

export default function Page() {
  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{
        __html: JSON.stringify(data).replace(/</g, '\\u003c'),
      }}
    />
  )
}
```

Never throws for an unchanged recipe from [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe) or [`fromJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonld), though an error thrown by a getter or proxy in the recipe or options passes through. For a recipe you build that `parseRecipe` never returns, it also throws `invalid_argument`, such as for servings whose `max` isn't greater than their amount, and can throw [`unknown_unit`](https://recipe-book.siraj.page/errors/unknown_unit.md) for an ingredient quantity, or one of its equivalents, whose unit isn't a unit ID. Either message names `toJsonLd`. An ingredient quantity, or one of its equivalents, throws `invalid_argument` at any `servings` and `system` when it isn't a quantity object, when its amount isn't a finite number greater than 0 or a range of them, when a range's `min` is greater than its `max`, or when it has a `max`, as a yield has. The message gives its path after `toJsonLd`, such as `toJsonLd: ingredients[0].items[0].equivalents[0]:`. Other quantities `parseRecipe` never returns, such as a range whose ends are equal or one with an extra key, are written, and equivalents on an ingredient with no quantity aren't checked or written. A finite amount, or an end of a range, above 1e290 or between 0 and 1e-300 isn't checked: it's written, or throws `invalid_argument` without a path where scaling or conversion makes it `Infinity` or 0.

`toJsonLd` doesn't check that its recipe was parsed, as [Errors](https://recipe-book.siraj.page/reference/core/errors.md) says. So a recipe you build can throw a `TypeError`, not a `RecipeBookError`, when its sections or items aren't objects, when its sections have no `items` array, or when its ingredient items have a quantity but no `equivalents` array. A `null` or `undefined` ingredient or equipment item throws one, and so does a section whose `items` is `null`. Any other equipment item without a `name`, such as a string, puts `undefined` in `tool`, which `JSON.stringify` writes as `null`, and a step item without `text`, such as `null` or a string, is written as a `HowToStep` whose `text` is `undefined`.

## Types

### `FromJsonLdResult`

```ts
type FromJsonLdResult = ParseResult<Recipe> & {
  extra: Record<string, unknown>
}
```

What [`fromJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonld) returns: a [`ParseResult<Recipe>`](https://recipe-book.siraj.page/reference/core/parsing.md#parseresult) with `extra` on success and failure alike.

| Name    | Type                      | Description                                                                                                                                   |
| ------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `extra` | `Record<string, unknown>` | The Recipe node's fields that the recipe doesn't model, other than `@context` and `@type`, as they were, or `{}` when there's no Recipe node. |

### `FromJsonLdOptions`

```ts
type FromJsonLdOptions = ParseQuantityOptions
```

The options for [`fromJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonld): the [`ParseQuantityOptions`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantityoptions) `decimal` and `units`. `decimal` applies to every amount in the page's text, and `units` to the units in `recipeIngredient` lines. A `QuantitativeValue`'s `value` is read as a number, and the yield's unit and `servingSize` are kept as written, so neither option applies to them.

### `ToJsonLdOptions`

```ts
type ToJsonLdOptions = {
  servings?: number | undefined
  system?: System | undefined
  url?: string | undefined
  idPrefix?: string | undefined
  extra?:
    | ({ [K in Modelled]?: SchemaOrgRecipe[K] | undefined } & Record<
        string,
        unknown
      >)
    | undefined
}

type Modelled =
  | 'name'
  | 'description'
  | 'image'
  | 'recipeYield'
  | 'prepTime'
  | 'cookTime'
  | 'totalTime'
  | 'recipeIngredient'
  | 'recipeInstructions'
  | 'tool'
  | 'nutrition'
```

Options for [`toJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld). An option that isn't valid uses its default. `Modelled` names the fields `toJsonLd` writes from a recipe; it isn't exported.

| Name       | Type                                                                                     | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| ---------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `servings` | `number \| undefined`                                                                    | The servings to write the recipe at, scaled as [`resolveRecipe`](https://recipe-book.siraj.page/reference/core/resolving.md#resolverecipe) scales it. Defaults to the recipe's own.                                                                                                                                                                                                                                                                                                                                |
| `system`   | [`System`](https://recipe-book.siraj.page/reference/core/units.md#system) \| `undefined` | The measurement system to write quantities in. Defaults to `recipe.system`, then `'metric'`.                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `url`      | `string \| undefined`                                                                    | The recipe page's URL. Each step gets it as its `url`, with `idPrefix` and the step's `id`, percent-encoded, as the fragment, so give each step's element that `id`. A fragment in `url` is replaced. When `url` is empty or only whitespace, steps have no `url`. When `url` is an absolute URL, a relative `image` is [resolved against it](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld).                                                                                               |
| `idPrefix` | `string \| undefined`                                                                    | Comes before each step's `id` in its `url`, to match the IDs your page gives the steps' elements, such as `'pancakes-'` for `#pancakes-step-1`. [`<Recipe.Step>`](https://recipe-book.siraj.page/reference/react/steps.md#step) renders its Root's `idPrefix` this way, and [`<Recipe.JsonLd>`](https://recipe-book.siraj.page/reference/react/json-ld.md#step-ids) passes it here. To match a Root that keeps its default, pass `` `${recipe.id}-` ``. Defaults to none.                                          |
| `extra`    | `Record<string, unknown> \| undefined`                                                   | schema.org fields the recipe doesn't model, such as `author`, `datePublished`, or `keywords`, written as you pass them. A field `toJsonLd` writes wins, and a field that's `undefined` is left out, so `{ image: maybeImage }` adds an image only when there is one. A `Modelled` field takes the type [`SchemaOrgRecipe`](https://recipe-book.siraj.page/reference/core/schema-org.md#schemaorgrecipe) gives it, so an `image` must be a URL string. Pass the `extra` from `fromJsonLd` to write its fields back. |

### `ToJsonLdResult`

```ts
type ToJsonLdResult = { data: SchemaOrgRecipe; warnings: RecipeIssue[] }
```

What [`toJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld) returns.

| Name       | Type                                                                                             | Description                                                                                                                              |
| ---------- | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `data`     | [`SchemaOrgRecipe`](https://recipe-book.siraj.page/reference/core/schema-org.md#schemaorgrecipe) | The recipe as a schema.org Recipe, with the fields from the `extra` option.                                                              |
| `warnings` | [`RecipeIssue[]`](https://recipe-book.siraj.page/reference/core/errors.md#recipeissue)           | The issues listed under [`toJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld), or `[]` when there are none. |

### `SchemaOrgRecipe`

```ts
type SchemaOrgRecipe = {
  '@context': 'https://schema.org'
  '@type': 'Recipe'
  name: string
  description?: string
  image?: string
  recipeYield?: string[]
  prepTime?: string
  cookTime?: string
  totalTime?: string
  recipeIngredient?: string[]
  recipeInstructions?: (SchemaOrgHowToStep | SchemaOrgHowToSection)[]
  tool?: string[]
  nutrition?: SchemaOrgNutritionInformation
  [field: string]: unknown
}
```

What [`toJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld) returns as `data`: a schema.org Recipe, as plain JSON when `extra` is, so a Server Component can render it. From `description` to `nutrition`, a field the recipe has no value for, including a `description` or `image` that's empty or only whitespace, comes from [`extra`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonldoptions), and a field neither has is absent. It's assignable to `WithContext<Recipe>` from [schema-dts](https://github.com/google/schema-dts), including under `exactOptionalPropertyTypes`, because an absent field's key is left out rather than set to `undefined`.

| Name                  | Type                                                                                                                                                                                                                         | Description                                                                                                                                                                                                                                                       |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `'@context'`          | `'https://schema.org'`                                                                                                                                                                                                       | The schema.org context. `extra` can't replace it.                                                                                                                                                                                                                 |
| `'@type'`             | `'Recipe'`                                                                                                                                                                                                                   | The schema.org type. `extra` can't replace it.                                                                                                                                                                                                                    |
| `name`                | `string`                                                                                                                                                                                                                     | The recipe's name.                                                                                                                                                                                                                                                |
| `description?`        | `string`                                                                                                                                                                                                                     | The recipe's description.                                                                                                                                                                                                                                         |
| `image?`              | `string`                                                                                                                                                                                                                     | The recipe's image, an http or https URL. A relative one is resolved against the [`url` option](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonldoptions), and stays relative without an absolute `url`.                                       |
| `recipeYield?`        | `string[]`                                                                                                                                                                                                                   | The servings as a number and as text, then the yield, such as `['4', '4 servings', '24 cookies']`. Fractional amounts are written as decimals, as in `['2.5', '2.5 servings', '1.25 loaves']`. Ranges stay ranges, as in `['4–6', '4–6 servings', '2–3 loaves']`. |
| `prepTime?`           | `string`                                                                                                                                                                                                                     | The prep time as an ISO 8601 duration, such as `'PT1H30M'`, with part minutes rounded to the nearest second, as in `'PT20M30S'`. A time that rounds to 0 seconds, or is longer than `Number.MAX_SAFE_INTEGER` minutes, counts as no value.                        |
| `cookTime?`           | `string`                                                                                                                                                                                                                     | The cook time, written as `prepTime` is.                                                                                                                                                                                                                          |
| `totalTime?`          | `string`                                                                                                                                                                                                                     | The total time, written as `prepTime` is.                                                                                                                                                                                                                         |
| `recipeIngredient?`   | `string[]`                                                                                                                                                                                                                   | One line per ingredient, across all sections, such as `'1 ½ cups (190 g) all-purpose flour'`.                                                                                                                                                                     |
| `recipeInstructions?` | ([`SchemaOrgHowToStep`](https://recipe-book.siraj.page/reference/core/schema-org.md#schemaorghowtostep) \| [`SchemaOrgHowToSection`](https://recipe-book.siraj.page/reference/core/schema-org.md#schemaorghowtosection))`[]` | The steps in order, with each titled section that has steps as a `HowToSection`.                                                                                                                                                                                  |
| `tool?`               | `string[]`                                                                                                                                                                                                                   | The equipment's names.                                                                                                                                                                                                                                            |
| `nutrition?`          | [`SchemaOrgNutritionInformation`](https://recipe-book.siraj.page/reference/core/schema-org.md#schemaorgnutritioninformation)                                                                                                 | Nutrition for one serving.                                                                                                                                                                                                                                        |
| `[field: string]`     | `unknown`                                                                                                                                                                                                                    | A field from the `extra` option that `toJsonLd` didn't write, with the value you passed.                                                                                                                                                                          |

### `SchemaOrgHowToStep`

```ts
type SchemaOrgHowToStep = {
  '@type': 'HowToStep'
  name?: string
  text: string
  image?: string
  url?: string
}
```

A step in a [`SchemaOrgRecipe`](https://recipe-book.siraj.page/reference/core/schema-org.md#schemaorgrecipe), written from a recipe's [`Step`](https://recipe-book.siraj.page/reference/core/types.md#step).

| Name      | Type          | Description                                                                                                                                                                                                                  |
| --------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `'@type'` | `'HowToStep'` | The schema.org type.                                                                                                                                                                                                         |
| `name?`   | `string`      | The step's name. It's absent when the step's name is missing, empty, or only whitespace.                                                                                                                                     |
| `text`    | `string`      | The step's text.                                                                                                                                                                                                             |
| `image?`  | `string`      | The step's image URL, resolved as the recipe's `image` is. It's absent when the step's image is missing, empty, or only whitespace.                                                                                          |
| `url?`    | `string`      | The `url` option with the `idPrefix` option and the step's `id`, percent-encoded, as the fragment, such as `'https://example.com/pancakes#step-1'`. It's absent when the `url` option is missing, empty, or only whitespace. |

### `SchemaOrgHowToSection`

```ts
type SchemaOrgHowToSection = {
  '@type': 'HowToSection'
  name: string
  itemListElement: SchemaOrgHowToStep[]
}
```

A titled section of steps in a [`SchemaOrgRecipe`](https://recipe-book.siraj.page/reference/core/schema-org.md#schemaorgrecipe). Steps in a section without a title, or whose title is empty or only whitespace, are written as steps, without a `HowToSection`.

| Name              | Type                                                                                                       | Description                    |
| ----------------- | ---------------------------------------------------------------------------------------------------------- | ------------------------------ |
| `'@type'`         | `'HowToSection'`                                                                                           | The schema.org type.           |
| `name`            | `string`                                                                                                   | The section's title.           |
| `itemListElement` | [`SchemaOrgHowToStep`](https://recipe-book.siraj.page/reference/core/schema-org.md#schemaorghowtostep)`[]` | The section's steps, in order. |

### `SchemaOrgNutritionInformation`

```ts
type SchemaOrgNutritionInformation = {
  '@type': 'NutritionInformation'
  servingSize?: string
  calories?: string
  fatContent?: string
  saturatedFatContent?: string
  transFatContent?: string
  unsaturatedFatContent?: string
  carbohydrateContent?: string
  sugarContent?: string
  fiberContent?: string
  proteinContent?: string
  sodiumContent?: string
  cholesterolContent?: string
}
```

Nutrition for one serving in a [`SchemaOrgRecipe`](https://recipe-book.siraj.page/reference/core/schema-org.md#schemaorgrecipe), written from a recipe's [`Nutrition`](https://recipe-book.siraj.page/reference/core/types.md#nutrition) as text with units, each amount rounded to three decimal places. Each field is absent when the recipe's nutrition doesn't have it or it's empty or only whitespace.

| Name                     | Type                     | Description                                                       |
| ------------------------ | ------------------------ | ----------------------------------------------------------------- |
| `'@type'`                | `'NutritionInformation'` | The schema.org type.                                              |
| `servingSize?`           | `string`                 | The serving size, as the recipe gives it, such as `'3 pancakes'`. |
| `calories?`              | `string`                 | Energy in kcal, such as `'250 kcal'`.                             |
| `fatContent?`            | `string`                 | Fat in grams, such as `'12 g'`.                                   |
| `saturatedFatContent?`   | `string`                 | Saturated fat in grams.                                           |
| `transFatContent?`       | `string`                 | Trans fat in grams.                                               |
| `unsaturatedFatContent?` | `string`                 | Unsaturated fat in grams.                                         |
| `carbohydrateContent?`   | `string`                 | Carbohydrates in grams.                                           |
| `sugarContent?`          | `string`                 | Sugar in grams.                                                   |
| `fiberContent?`          | `string`                 | Fiber in grams.                                                   |
| `proteinContent?`        | `string`                 | Protein in grams.                                                 |
| `sodiumContent?`         | `string`                 | Sodium in milligrams, such as `'500 mg'`.                         |
| `cholesterolContent?`    | `string`                 | Cholesterol in milligrams.                                        |
