Skip to content

Instantly share code, notes, and snippets.

@jbaranski
Created August 1, 2020 14:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbaranski/2c652233c6cc4916d2513f4131aa3233 to your computer and use it in GitHub Desktop.
Save jbaranski/2c652233c6cc4916d2513f4131aa3233 to your computer and use it in GitHub Desktop.
Read in YAML or JSON file using Python

The following code will read in a YAML file and store it in a dictionary. The dictionary content is then printed to the console.

config.yaml

test: value
nested:
  test: nestedValue

script.py

import json
import yaml

config = {}
with open("config.yml", "r") as stream:
    config = yaml.safe_load(stream)
    # config = json.load(stream) to load JSON data

print(config['test'])
print(config['nested']['test'])
print(json.dumps(config, indent=4))

console output

value
nestedValue
{
    "test": "value",
    "nested": {
        "test": "nestedValue"
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment