简体   繁体   中英

How to add contents to YAML file using ruamel.yaml?

Here is the input.yml file

PRODUCT_HOME: /app
config: 
  active-profiles: mysql,oauth2
  driverClassName: com.mysql.cj.jdbc.Driver
  datasourceurl: jdbc:h2:file:./data
  datasourceuser: sa
server:
  error:
    path: /error
  whitelabel:
    enabled: false
  port: 8080

Output file should look like:

PRODUCT_HOME: /app
config: 
  active-profiles: mysql,oauth2
  driverClassName: com.mysql.cj.jdbc.Driver
  datasourceurl: jdbc:h2:file:./data
  datasourceuser: sa
server:
   error:
      path: /error
   whitelabel:
      enabled: false
   port: 8080
   servlet:
     session:
       cookie:
         secure: true

How can I achieve this using Python (ruamel.yaml) package?

You should create the correct data structure for the data you want to add and then add that datastructure to the mapping that is the value of server

import sys
import ruamel.yaml

from pathlib import Path

in_file = Path('input.yaml')
    
nd = dict(servlet=dict(session=dict(cookie=dict(secure=True))))

yaml = ruamel.yaml.YAML()
data = yaml.load(in_file)
data['server'].update(nd)

# print(data)
yaml.dump(data, sys.stdout)

which gives:

PRODUCT_HOME: /app
config:
  active-profiles: mysql,oauth2
  driverClassName: com.mysql.cj.jdbc.Driver
  datasourceurl: jdbc:h2:file:./data
  datasourceuser: sa
server:
  error:
    path: /error
  whitelabel:
    enabled: false
  port: 8080
  servlet:
    session:
      cookie:
        secure: true

Alternatively, if you have the data to add as YAML input you can load that and then update:

yaml_str = """
servlet:
  session:
    cookie:
      secure: true
"""

yaml = ruamel.yaml.YAML()
nd = yaml.load(yaml_str)
data = yaml.load(in_file)
data['server'].update(nd)

# print(data)
yaml.dump(data, sys.stdout)

which also gives:

PRODUCT_HOME: /app
config:
  active-profiles: mysql,oauth2
  driverClassName: com.mysql.cj.jdbc.Driver
  datasourceurl: jdbc:h2:file:./data
  datasourceuser: sa
server:
  error:
    path: /error
  whitelabel:
    enabled: false
  port: 8080
  servlet:
    session:
      cookie:
        secure: true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM