gpt4 book ai didi

python - 如何使用dictionary/json在yaml中添加 '-'?

转载 作者:行者123 更新时间:2023-12-01 09:18:36 24 4
gpt4 key购买 nike

我有以下代码,它从字典创建 yaml 文件:

import yaml
from collections import OrderedDict
import json
from pprint import pprint
import random
import string
data = {
"test_name" : "Create_user test",

"stages":{
"name" : "check user sucessfully added",
"request": {
"url":"self.url",
"json":{
"username":"self.username",
"role":"self.role",
"userProfile":"self.userProfile"
},
"method":"self.method",
"headers":{"content_type":"application/json"}
},

"response" : {"status_code":200}
}
}
print(data)
def setup_yaml():
""" https://stackoverflow.com/a/8661021 """
represent_dict_order = lambda self, data: self.represent_mapping('tag:yaml.org,2002:map', data.items())
yaml.add_representer(OrderedDict, represent_dict_order)
setup_yaml()

with open('abc_try.tavern.yml', 'w') as outfile:
yaml.dump(OrderedDict(data), outfile, default_flow_style=False)

我得到的“abc_try.tavern.yml”文件为:

test_name: Create_user test
stages:
name: check user sucessfully added
request:
headers:
content_type: application/json
json:
role: self.role
userProfile: self.userProfile
username: self.username
method: self.method
url: self.url
response:
status_code: 200

但是我想要生成以下文件:

test_name: Create_user test
stages:
- name: check user sucessfully added
request:
headers:
content_type: application/json
json:
role: self.role
userProfile: self.userProfile
username: self.username
method: self.method
url: self.url
response:
status_code: 200

如何在第三行“name”之前添加“-”。(请注意“-”的间距和格式,即位于“stages”的“s”下方。

最佳答案

The '-' indicates a list element 。所以你必须将内部字典放入列表中:

data = {
"test_name" : "Create_user test",
"stages": [
{
"name" : "check user sucessfully added",
# ...
}
]
}

关于python - 如何使用dictionary/json在yaml中添加 '-'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51001914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com