3

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
3
  • Does this answer your question? Convert dot notation keys to tree-structured YAML in Ruby Commented Jan 6, 2020 at 13:40
  • that might help you, and also check out this for a more refined version. Commented Jan 6, 2020 at 14:24
  • How do you know that there has to be a sequence between the key c and the key d and not between the key b and c? It would be kind of obvious if your input was a.b.c.0.d, a.b.c.0.e, etc. but it isn't. Commented Jan 6, 2020 at 16:35

1 Answer 1

5

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'
Sign up to request clarification or add additional context in comments.

1 Comment

@MM I've seen your edit suggestion: it seems like a substantial change to me, so maybe you want to add this as a separate answer? I don't want to take credit for your work here, so I rejected the edit suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.