Extract data from yml to csv

Hi All, I am trying to extract the details from a yaml file and put into a csv file format as below:

Entity Name, Attribute Name
“Order”,“Customer Id”
“Order”,“Order Date”
“Order Items”,“Order Id”
“Order Items”,“Product Id”
“Order Items”,“Order Item Id”
“Order Items”,“Unit Price”
“Order Items”,“Unit Quantity”

Here is the sample input yml file.

swagger: “1.0”
info:
title: Order Details
version: 0.0.1
paths:
/structure:
post:
description: Generates JSON structure based on this model
consumes:
- application/json
produces:
- application/json
parameters:
- in: body
name: payload
description: generate structure
schema:
$ref: ‘#/definitions/payload’
responses:
200:
description: “Okay”
definitions:
payload:
type: object
properties:
order:
type: array
items:
$ref: ‘#/definitions/modelDefinition’
modelDefinition:
type: object
properties:
order_items:
$ref: ‘#/definitions/order_items’
customer id:
type: string
description: “Unique Identfier of Customer”
order date:
type: string
description: “Date Ordered”

References start below

order_items:
type: object
description: “”
properties:
order id:
type: string
description: “Unique Order ID”
order item id:
type: integer
description: “Unique Order Item”
product id:
type: integer
description: “Unique Product ID”
unit price:
type: string
description: “Price”
unit quantity:
type: string
description: “Quantity”
I created a python object using below code:

Imports the YAML module for use in our script

import yaml
#Opens the file ex1.yaml, and loads the contents in the variable ‘result’
with open(‘test.yaml’) as f:
data = yaml.safe_load(f)
print(data)

But I am not been able to get the required output looping through the nested dictionary created.
I also tried to extract the keys by iterating through data.items() but it is giving me only few keys.

Is there a way to get the desired result ? Thanks for your help on this.

Hey,

This might be helpful.

Thanks for the link. I followed this link but did not help to solve my problem

Use yaml.safe_load through a context manager to convert a YAML file to JSON-style dictionary, convert in into a dataframe using pandas.json_normalize, narrow it down to columns you like using df.loc and export it to CSV using df.to_csv.