2020-06-13
|~1 min read
|186 words
I like pretty things. Particularly when they hold the answer to my questions!
As a result, when working with objects (aka Dictionaries in Python), I prefer not to have to parse a wall of text (even if it’s small like so:
my json is --> {'file_prefix': 'emm_leads_data', 'staging_schema': 'army_stage', 'stagi
ng_table': 'emm_leads_raw', 'has_header': False, 'write_mode': 'Append'}
With Javascript, I can use JSON.Stringify’s spacer argument to convert the wall of text into a formatted object:
console.log(`my json is --> ${JSON.stringify(myObj, null, 4)}`)
my json is --> {
"file_prefix": "emm_leads_data",
"has_header": false,
"staging_schema": "army_stage",
"staging_table": "emm_leads_raw",
"write_mode": "Append"
}
Python has a similarly easy method for achieving this using the json dumps
method1 and passing in an indent argument:
def pretty_print_json(val):
print(f"The pretty json is --> {json.dumps(val, indent=4)}")
Of course this can be simplified to:
def pretty_print_json(val):
print(json.dumps(val, indent=4)})
And just like that, I can read my outputs again!
json.dump
and json.dumps
method. In this case we’re using dumps
(with an s
). For more on the differences, this PYnative article seems useful.Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!