1

I have a python script that downloads file_content from repo using repo.get_contents. so I have used -

contents = repo.get_contents(
    './some_file.yaml', ref='master').decoded_content.decode()

And now I have the content of the yaml file as a string of - \nkey1:\n-a\n-b-n-c\nkey2

How can I convert it to dict with keys and values? Can I pull it to dict using the function? or convert this string somehow?

EilonA
  • 361
  • 5
  • 17

2 Answers2

2

It might be a duplicated question. how-do-i-parse-a-yaml-string-with-python

import yaml

dct = yaml.safe_load('''
name: John
age: 30
automobiles:
- brand: Honda
  type: Odyssey
  year: 2018
- brand: Toyota
  type: Sienna
  year: 2015
''')
assert dct['name'] == 'John'
assert dct['age'] == 30
assert len(dct["automobiles"]) == 2
assert dct["automobiles"][0]["brand"] == "Honda"
assert dct["automobiles"][1]["year"] == 2015
Minh Dao
  • 827
  • 8
  • 21
0

You can use PyYAML

pip install pyyaml

Run your code as shown bellow :

import yaml

yml_file = #your yml file

json_file = yaml.load(yml_file)
  • I have a yaml file in the repo, not in my directories. Get_content just downloads the content into a variable. Therefore, I can't do yaml.load.. I have only the string of keys and values separated by "\n" – EilonA Jan 12 '22 at 08:18