yaml files into python dictionary

misalkan script yaml seperti dibawah ini (ambil dari kubernetes) :

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: nginx
    spec:
      nodeSelector:
        kubernetes.io/hostname: worker0
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80

lalu buat program pythonnya :

import yaml

# open json and read into raw text
raw = open('inventory.yaml').read()

# loads the raw into loads() function to create dict
data = yaml.load(raw)

# check data type
print ("\nType data :")
print (type(data))

# check the data
print ("\nAll data :")
print (data)

berikut outputnya :

zufar@zufar:~/Documents/Technology/Programming/Python/telnetlib$ python lab4.py

Type data :
<type 'dict'>

All data :
{'kind': 'Deployment', 'spec': {'template': {'spec': {'containers': [{'image': 'nginx', 'name': 'nginx', 'ports': [{'containerPort': 80}]}], 'nodeSelector': {'kubernetes.io/hostname': 'worker0'}}, 'metadata': {'labels': {'app': 'nginx'}}}, 'replicas': 1}, 'apiVersion': 'extensions/v1beta1', 'metadata': {'name': 'nginx'}}

 

Comments are closed.