0

I want to search for a key in a nested YAML file. I have the path for the key as user/name/firstname . I am loading the YAML file using ruamel.yaml and I have set off the path to the keys.

Now I want to look for the key using the path in the exact same pattern.

I am generating this path using flat_keys = flatten(data , reducer='path'). and using processor.set_value(yaml_path,new_value) to update value. But before updating, I want to check if the key exists in the given path.

sample:

user:
    name:
        firstname:
        lastname:

Is there a way to do that?

Anthon
  • 69,918
  • 32
  • 186
  • 246
Ahalya Hegde
  • 1,571
  • 2
  • 18
  • 41

2 Answers2

0

Instead of using ruamel I would rather prefer benedict library - https://github.com/fabiocaccamo/python-benedict

Here, I'm checking if path exists and updating the path with new value

n [1]: from benedict import benedict
   ...:

In [2]: a = """user:
   ...:     name:
   ...:         firstname:
   ...:         lastname:
   ...:         """

In [3]: d = benedict(a, format="yaml")

In [4]: d
Out[4]: {'user': {'name': {'firstname': None, 'lastname': None}}}

In [5]: path = "user/name/firstname"

In [6]: path.replace("/",".") in  d
Out[6]: True

In [7]: path = "user/lastname"

In [8]: path.replace("/",".") in  d
Out[8]: False

In [14]: d[path.replace("/",".")] = "hello"

In [15]: d
Out[15]: {'user': {'name': {'firstname': None, 'lastname': None}, 'lastname': 'hello'}}
bigbounty
  • 16,526
  • 5
  • 37
  • 65
-1

# Sample YAML data
aliases:
  - &commonUsername username
  - &commonPassword 5uP3r 53kr17 P@55\/\/0rD

configuration::application:
  'general.settings':
    slash\key: ENC[some-lengthy-EYAML-value]
    'a.dotted.subkey':
      - element1
      - element2
      - element3

sensitive::accounts:
  database:
    app_user: *commonUsername
    app_pass: *commonPassword
  application:
    db:
      users:
        - name: admin
          pass: 1s0L@73d @cC0u|\|7
          access_level: 0
        - name: *commonUsername
          pass: *commonPassword
          access_level: 500
Poornima
  • 1
  • 1