英文:
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']}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论