簡體   English   中英

YAML to JSON with Python, Kubernetes api call

[英]YAML to JSON with Python, Kubernetes api call

我想把這個文件轉換成json格式,有人知道怎么做嗎?

這是 yaml 文件:

apiVersion: v1
kind: Namespace
metadata:
  name: theiaide
---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  #name: rewrite
  name: theiaide
  namespace: theiaide
  annotations:
    #nginx.ingress.kubernetes.io/rewrite-target: /$2
    kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: ide.quantum.com
    http:
      paths:
      - path: /
        backend:
          serviceName: theiaide
          servicePort: 80
---
apiVersion: v1
kind: Service
metadata:
 name: theiaide
 namespace: theiaide
spec:
 ports:
 - port: 80
   targetPort: 3000
 selector:
   app: theiaide
---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: theiaide
  name: theiaide
  namespace: theiaide
spec:
  selector:
    matchLabels:
      app: theiaide
  replicas: 1
  template:
    metadata:
      labels:
        app: theiaide
    spec:
      containers:
      - image: theiaide/theia-python
        imagePullPolicy: IfNotPresent
        name: theiaide
        ports:
        - containerPort: 3000

代碼.py

import json,yaml
txt=""
with open(r"C:\Users\77922\PycharmProjects\ide-ingress.yaml",'r') as f:
    for a in f.readlines():
        txt=txt+a
print(yaml.dump(yaml.load_all(txt),default_flow_style=False))
print(json.dumps(yaml.load_all(txt),indent=2,sort_keys=True))

當我運行 python code.py 時,我得到了錯誤:

TypeError: can't pickle generator objects

不知道是不是這個原因---分隔符,因為我的yaml文件中有多個---分隔符

然后我嘗試了以下function:

def main():

    # config.load_kube_config()

    f = open(r"C:\Users\77922\PycharmProjects\ide-ingress.yaml","r")
    generate_dict  = yaml.load_all(f,Loader=yaml.FullLoader)
    generate_json = json.dumps(generate_dict)
    print(generate_json)
    # dep = yaml.load_all(f)
    # k8s_apps_v1 = client.AppsV1Api()
    # resp = k8s_apps_v1.create_namespaced_deployment(
    #     body=dep, namespace="default")
    # print("Deployment created. status='%s'" % resp.metadata.name)
if __name__ == '__main__':
    main()

 raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type generator is not JSON serializable

我只想使用這個 yaml 文件來調用 kubernetes api 來生成命名空間

您的文件包含多個文檔。 您應該使用safe_load_all function 而不是yaml.loadlist而不是json.dumps

import json,yaml
txt=""
with open(r"C:\Users\77922\PycharmProjects\ide-ingress.yaml",'r') as f:
    for a in f.readlines():
        txt=txt+a
print(yaml.dump_all(yaml.safe_load_all(txt),default_flow_style=False))
print(list(yaml.safe_load_all(txt)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM