Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert dot separated string into yaml format using python script

I am having a file having some properties myprop.properties

a.b.c.d : '0'
a.b.c.e : 'hello'
a.b.c.f : 'hello1'
a.b.g.h : '123'
a.b.g.i : '4567'
http_port : false
install_java : true

I want to dump this file into yaml format, so the expected output should be:

a:
 b:
  c:
  - d: '0'
    e: hello
    f: hello1
  g:
  - h: '123'
    i: '4567'
http_port : false
install_java : true
like image 260
Priya Avatar asked Feb 25 '26 03:02

Priya


1 Answers

using this nice recursive function, you could convert your dotmap string to a dict and then do a yaml.dump:

def add_branch(tree, vector, value):
    key = vector[0]
    if len(vector) == 1:
        tree[key] = value  
    else: 
        tree[key] = add_branch(tree[key] if key in tree else {}, vector[1:], value)
    return tree

dotmap_string = """a.b.c.d : '0'
a.b.c.e : 'hello'
a.b.c.f : 'hello1'
a.b.g.h : '123'
a.b.g.i : '4567'
http_port : false
install_java : true"""

# create a dict from the dotmap string:
d = {}
for substring in dotmap_string.split('\n'):
    kv = substring.split(' : ')
    d = add_branch(d, kv[0].split('.'), kv[1])

# now convert the dict to YAML:
import yaml    
print(yaml.dump(d))  
# a:
#   b:
#     c:
#       d: '''0'''
#       e: '''hello'''
#       f: '''hello1'''
#     g:
#       h: '''123'''
#       i: '''4567'''
# http_port: 'false'
# install_java: 'true'
like image 107
FObersteiner Avatar answered Feb 26 '26 17:02

FObersteiner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!