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

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

Python convert raw text to Yaml or Json

问题

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

  1. image: artifactory.test.com/hello:v1
  2. stages:
  3. - build
  4. build-job-example:
  5. stage: build
  6. script:
  7. - echo "Building the 'Hello World' app"
  8. - python3 --version
  9. only:
  10. - 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

  1. image: artifactory.test.com/hello:v1
  2. stages:
  3. - build
  4. build-job-example:
  5. stage: build
  6. script:
  7. - echo "Building the 'Hello World' app"
  8. - python3 --version
  9. only:
  10. - 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()

例如:

  1. import yaml
  2. yml_str = """
  3. image: artifactory.test.com/hello:v1
  4. stages:
  5. - build
  6. build-job-example:
  7. stage: build
  8. script:
  9. - echo "Building the 'Hello World' app"
  10. - python3 --version
  11. only:
  12. - main
  13. """
  14. yml = yaml.safe_load(yml_str)
  15. print(yml['build-job-example'])

输出:

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

You can use yaml.safe_load()

For instance:

  1. import yaml
  2. yml_str = """
  3. image: artifactory.test.com/hello:v1
  4. stages:
  5. - build
  6. build-job-example:
  7. stage: build
  8. script:
  9. - echo "Building the 'Hello World' app"
  10. - python3 --version
  11. only:
  12. - main
  13. """
  14. yml = yaml.safe_load(yml_str)
  15. print(yml['build-job-example'])

Ouput:

  1. {'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:

确定