Python将原始文本转换为Yaml或Json

huangapple go评论61阅读模式
英文:

Python convert raw text to Yaml or Json

问题

有没有办法将原始文本的YAML格式数据转换成YAML文件或JSON。
我得到的响应中有原始文件数据,如下:

image: artifactory.test.com/hello:v1
stages:
  - build

build-job-example:
  stage: build
  script:
    - echo "Building the 'Hello World' app"
    - python3 --version
  only:
    - main

如何将其转换为YAML,以便我可以编辑内容并推送到GitLab。
我的目标是根据键替换一些值并提交。

英文:

Is there any way where we can convert raw text yaml formatted data to yaml file or json.
I'm getting a raw file data in response as

image: artifactory.test.com/hello:v1
stages:
  - build

build-job-example:
  stage: build
  script:
    - echo "Building the 'Hello World' app"
    - python3 --version
  only:
    - main

How do I convert it into a yaml, so that I can edit the contents and push to gitlab.
My aim it to replace few values with respect to key and commit.

答案1

得分: 1

你可以使用 yaml.safe_load()

例如:

import yaml

yml_str = """
image: artifactory.test.com/hello:v1
stages:
  - build

build-job-example:
  stage: build
  script:
    - echo "Building the 'Hello World' app"
    - python3 --version
  only:
    - main
"""

yml = yaml.safe_load(yml_str)
print(yml['build-job-example'])

输出:

{'stage': 'build', 'script': ['echo "Building the \'Hello World\' app"', 'python3 --version'], 'only': ['main']}
英文:

You can use yaml.safe_load()

For instance:

import yaml

yml_str = """
image: artifactory.test.com/hello:v1
stages:
  - build

build-job-example:
  stage: build
  script:
    - echo "Building the 'Hello World' app"
    - python3 --version
  only:
    - main
"""

yml = yaml.safe_load(yml_str)
print(yml['build-job-example'])

Ouput:

{'stage': 'build', 'script': ['echo "Building the \'Hello World\' app"', 'python3 --version'], 'only': ['main']}

huangapple
  • 本文由 发表于 2023年3月7日 16:10:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75659393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定