【问题标题】:Python - downloading a yaml file from github using PyGitHub get_contents and trying to convert it to dictPython - 使用 PyGitHub get_contents 从 github 下载 yaml 文件并尝试将其转换为 dict
【发布时间】:2022-01-12 08:04:49
【问题描述】:

我有一个 python 脚本,它使用 repo.get_contents 从 repo 下载 file_content。 所以我用过-

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

现在我将 yaml 文件的内容作为字符串 - \nkey1:\n-a\n-b-n-c\nkey2

如何将其转换为带有键和值的 dict? 我可以使用该功能将其拉到 dict 吗?或者以某种方式转换这个字符串?

【问题讨论】:

    标签: python json dictionary yaml


    【解决方案1】:

    这可能是一个重复的问题。 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
    

    【讨论】:

      【解决方案2】:

      您可以使用PyYAML

      pip install pyyaml
      

      如下所示运行您的代码:

      import yaml
      
      yml_file = #your yml file
      
      json_file = yaml.load(yml_file)
      

      【讨论】:

      • 我在 repo 中有一个 yaml 文件,而不是在我的目录中。 Get_content 只是将内容下载到一个变量中。因此,我不能做 yaml.load.. 我只有用“\n”分隔的键和值的字符串
      猜你喜欢
      • 2012-10-12
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-30
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多