I'm using Drupal 9 with Commerce 2. I have a large number of product types that need to be created. I have for each product type which fields need to be added. Let's say this information is stored in a json (I can vary this if the solution requires it). I was wondering if there is a way to create a module or something that iterates through this json file, and it creates all the product types. If there is, how would I go about implementing this?
I found some code examples with which I can create products programmatically here. I'm just not entirely sure how I would use this code inside a custom module.
There is no way, just custom code all the way down. That said, it may be to your advantage not to have a proliferation of product types. They do create overhead on your site. Might be better simply to have optional fields on fewer, especially if their creation will be automated? Could always have a sub-type field on the product type itself that controls which fields are shown on the edit form via form states and even make various fields conditionally required.
I havent done this exactly with Commerce Entities, but I have done with custom entities using Migrate API.
What you can do is provide json or csv migrate source to migration and map those fields accordingly in my_products_migration.yml file , you can use contribute modules like, migrate_plus, migrate_source_csv you can even refer migrate_json_example module from migrate_plus which has a reference example for products migration.