使用Python、Kubernetes api调用从YAML到JSON

2024-10-03 09:09:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把这个文件转换成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

code.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文件中有多个---分隔符

然后我尝试了以下功能:

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来生成名称空间


Tags: 文件nametxtjsonappyamlloadnamespace
1条回答
网友
1楼 · 发布于 2024-10-03 09:09:21

您的文件包含多个文档。您应该使用safe_load_all函数而不是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)))

相关问题 更多 >