ThisCalculator

Everyday

Parse Gherkin Feature Files to JSON

Updated · Standard formula, shown below

Parse Gherkin Feature Files to JSON

To parse a Gherkin feature file into JSON, use a Gherkin parser that understands the language grammar, then serialize the parser’s structured result as JSON. The output can represent features, scenarios, steps, tags, and data tables; it is not simply the original text split at keywords.

What Gherkin-to-JSON Parsing Means

Gherkin is a human-readable syntax commonly used to describe software behavior in feature files. A typical file uses keywords such as Feature, Scenario, Given, When, and Then. Cucumber tools and related test frameworks parse these files so they can identify the structure and connect steps to executable step definitions.

JSON is one possible format for representing that structure. A parser may return a syntax tree or an intermediate document containing feature metadata, scenario definitions, step text, tags, and locations. The exact JSON shape depends on the parser and its version. There is no single universal JSON format that every Gherkin tool must produce.

Choose the Right Parser and Output

Start by checking what you need the JSON for. If you are building an editor, analysis tool, or custom test runner, a parser’s abstract syntax tree or document model is usually more useful than a report. If you need results from a test run, use the test framework’s reporting or message output instead: parsing source code describes what tests say, not whether they passed.

  • Use the parser library for your ecosystem when your application needs to inspect or transform feature files.
  • Use a command-line formatter when you only need a generated report and the installed test runner supports a JSON formatter.
  • Use a Gherkin-compatible parser rather than regular expressions when syntax details such as tables, doc strings, tags, and language settings matter.

Check the tool’s documentation for its package name, API, command-line options, and output schema. These details differ across Cucumber implementations and releases; a command that works in one language or version may not work in another.

How Parsing Works

A parser reads the source according to Gherkin grammar. It recognizes the feature and scenario hierarchy, associates step keywords with their text, and handles syntax that spans multiple lines. Depending on the API, it may also produce tokens, source locations, or diagnostics alongside the parsed document.

Consider this feature:

Feature: Account access
  Scenario: Sign in with valid details
    Given an active account
    When the user signs in
    Then the account page is shown

A structured representation could contain a feature named “Account access,” one scenario, and three steps in order. Illustrative JSON might look like this:

{
  "feature": {
    "name": "Account access",
    "scenarios": [
      {
        "name": "Sign in with valid details",
        "steps": [
          { "keyword": "Given", "text": "an active account" },
          { "keyword": "When", "text": "the user signs in" },
          { "keyword": "Then", "text": "the account page is shown" }
        ]
      }
    ]
  }
}

This is an explanatory shape, not a guarantee of any particular parser’s output. Some formats use nested nodes with different field names, include keyword spacing, or represent scenarios and rules with additional levels. Use the library’s actual schema when writing code that consumes its output.

Practical Parsing Steps

  1. Identify the implementation. Check the project’s language, test framework, and installed Gherkin or Cucumber dependencies.
  2. Read the file as text. Preserve its encoding and provide the parser the source it expects. Some APIs also accept a URI or source-location label.
  3. Call the documented parser API or formatter. Request a structured document or JSON output supported by that implementation.
  4. Handle parse errors. Report the file and location when available; do not silently turn invalid input into an empty feature.
  5. Inspect the result. Confirm that names, step order, tags, tables, and other constructs your application needs are present.
  6. Serialize or consume the result. If the parser returns an object rather than JSON text, use the language’s JSON serializer and define how unsupported values should be handled.

Syntax Details That Affect the JSON

Simple scenarios are only part of Gherkin. A robust parser matters when a file uses additional syntax:

  • Scenario outlines describe a template that can be run with multiple rows in an Examples table. A parser may preserve the outline and rows rather than expand them into separate scenarios.
  • Data tables attach rows and cells to a step. They are structured values, not ordinary words in the step text.
  • Doc strings provide multiline step content and may include a content type. A parser usually keeps this content separate from the step text.
  • Tags can apply to features, rules, or scenarios. Their placement and inheritance can matter to downstream tools.
  • Localized Gherkin uses language-specific keywords. The parser must recognize the file’s language, often indicated by a language directive.
  • Rules and backgrounds add hierarchy or shared context. Flattening everything into a list of steps can lose meaning.

These are common reasons that a hand-written regular expression seems to work on one file but fails on another. For instance, splitting each line at the word Given cannot correctly preserve a multiline doc string or distinguish a scenario outline from an ordinary scenario.

Common Problems and Misconceptions

A frequent misconception is that JSON parsing executes the scenarios. It does not. Parsing checks and structures the feature text; executing tests requires a runner, matching step definitions, and any required application or test environment.

Another source of trouble is expecting a stable schema without pinning or checking the tool version. If another program depends on particular JSON fields, treat the output format as an interface: consult its specification, handle missing or optional fields, and test against representative files.

When parsing fails, check for misspelled or misplaced keywords, malformed table rows, an incorrect language setting, or unsupported syntax for the parser version. Also verify that the file being parsed is the one you expect and that the process reports parser errors rather than swallowing them.

Frequently Asked Questions

Can I convert a .feature file to JSON without running tests?
Yes. A Gherkin parser can read and structure the source without executing any steps. Use a test runner only when you also need execution results.

Can I parse Gherkin with regular expressions?
You can extract simple patterns from tightly controlled files, but regular expressions are not a dependable substitute for a grammar-aware parser. Tables, doc strings, outlines, tags, and localized keywords make ad hoc parsing fragile.

Does every Gherkin parser produce the same JSON?
No. The document model and JSON schema depend on the library, formatter, and version. Confirm the output contract for the tool you choose.

How do I include test results in JSON?
Use the JSON or other machine-readable formatter provided by your test runner, if available. A source parser alone cannot report whether a step passed, failed, or was skipped.

Why does a parser reject a feature file that looks readable?
Gherkin has syntax rules beyond plain English. Check keyword placement, table formatting, language configuration, and parser compatibility, then use any reported line and column to locate the issue.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.