![]() It's probably not worthwhile to build your own function to achieve this unless you spend some time to optimize it, and with the lack of a builtin for the same, it's probably best you stick with your gun since your efforts will most likely give diminishing returns. It prints pretty alright, and unsurprisingly it took a whooping 16.701202023s to run in timeit(number=10000), which is 3 times as much as a json.dumps(json.loads()) would get you. Print(indentor*(0 if j in '' else ind_lvl) temp.strip() c) Print(indentor*ind_lvl temp.strip() '\n' indentor*(ind_lvl-1) c, end='') Print(indentor*ind_lvl temp.strip() c) Just for fun I whipped up the following function: def pretty_json_for_savages(j, indentor=' '): As well it doesn't retain the order in which the items appeared, so it's not great if order is important for readability. I tried with pprint, but it actually wouldn't print the pure JSON string unless it's converted to a Python dict, which loses your true, null and false etc valid JSON as mentioned in the other answer. timeit(number=10000) for the following took about 5.659214497s: import json I think for a true JSON object print, it's probably as good as it gets. The output will produce valid JSON, whereas pprint will not. Thanks for pointing out my errors along the way. json.dumps (obj, indent2) is better than pprint because: It is faster with the same load methodology. >164241 function calls (140121 primitive calls) in 0.208 seconds > 71027 function calls (42309 primitive calls) in 0.084 seconds Pretty_json = json.dumps(json.load(resp), indent=2)
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |