Parsing Cucumber Feature Files into JSON or NDJSON using Java with Cucumber 7.6.0 or Gherkin-Java 24.0.0

Viewed 91

Background of the Question:

Earlier Issue:

I have already asked this question in the past with attached thread below but the use case was different in that case. I just needed a way to print the JSON into stdout using (NodeJS) cucumber-js. I used Native Cucumber parsing using cucumber CLI commands as per (https://github.com/cucumber/cucumber-js/blob/main/docs/formatters.md).

How to convert cucumber gherkin feature files into JSON or AST format?

Current Issue: I want to Parse Gherkin Feature Files to JSON using Java. These JSON files would be later interpreted and rendered into a front end dashboard where we could filter feature files based on tags, scenarios and text match for features.

I came through React cucumber (https://github.com/cucumber/react-components) Library but this is more of a JS Based solution and I need to process the Parsed Feature file JSON before passing to the view layer.

Can someone please provide the code snippet for parsing Gherkin Feature file to JSON in Java. I went through below threads but all are using deprecated code.

Cucumber feature file - parsing to an object

How to parse Cucumber feature file in java or groovy?

and a few more.

Please provide an example code snippet if possible. Thanks in Advance :)

1 Answers

You can use io.cucumber.junit.Cucumber for reference. Briefly in your case you would do the following:

public class Main {
 
    public static void main(String[] args){
     
        RuntimeOptions runtimeOptions = new CucumberPropertiesParser()
                .parse(CucumberProperties.fromSystemProperties())
                .addDefaultFeaturePathIfAbsent()
                .build();

        SynchronizedEventBus bus = synchronize(new TimeServiceEventBus(Clock.systemUTC(), UUID::randomUUID));

        FeatureParser parser = new FeatureParser(bus::generateId);
        Supplier<ClassLoader> classLoader = ClassLoaders::getDefaultClassLoader;
        FeaturePathFeatureSupplier featureSupplier = new FeaturePathFeatureSupplier(classLoader, runtimeOptions,
            parser);
        List<Feature> features = featureSupplier.get();

        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println(objectMapper.writeWithDefaultPrettyPrinter().writeValueAsString(features));
    }
    
} 
Related