Search code examples
pythonjsondictionaryyamlordereddictionary

how to add '-' in yaml using dictionary/json?


I have the following code which creates a yaml file from dictionary:

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)

And I get the 'abc_try.tavern.yml' file as:

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

but the I want the following file to be generated:

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

How to add the '-' in third line before 'name'.(Kindly mind the spacing and formatting of '-', i.e. just below 's' of 'stages'.


Solution

  • The '-' indicates a list element. So you have to put the inner dict in a list:

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