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

标签 python json dictionary yaml ordereddictionary

我有以下代码,它从字典创建 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/

相关文章:

php - 带有 JSON 和 PHP 的 HTML5 服务器发送事件 (SSE)

swift - 在 Swift 中检查是否为 "dictionary item exists and is not blank"的紧凑方法?

c# - 按值复制字典

python - 包控制 : The dependency 'markupsafe' is not currently installed

php - 从多维数组数据生成json字符串

python - 如何使用 Python 在 map 上绘制可视化线串?

c# - 如何格式化Json输出?

c++ - 如何从 Photon eventContent 字典中获取数据

Python 错误 : null byte in input prompt

python - 如何在基类内部声明子类对象而不导致递归错误?