Home > front end >  Python - downloading a yaml file from github using PyGitHub get_contents and trying to convert it to
Python - downloading a yaml file from github using PyGitHub get_contents and trying to convert it to

Time:01-12

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?

CodePudding user response:

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

CodePudding user response:

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)
  •  Tags:  
  • Related