Python dict to json file pretty
Hopefully this helps someone else. Show In the case when there is a error that something is not json serializable the answers above will not work. If you only want to save it so that is human readable then you need to recursively call string on all the non dictionary elements of your dictionary. If you want to load it later then save it as a pickle file then load it (e.g. This is what worked for me:
output:
I don't
know why returning the string then printing it doesn't work but it seems you have to put the dumps directly in the print statement. Note Context: I wanted to save pytorch strings but I kept getting the error:
so I coded the above. Note that yes, in pytorch you use PPrint also has indent arguments but I didn't like how it looks:
output:
compare to:
How do I make JSON data look pretty?If you're starting from a valid JSON string that you want to pretty printed, you need to convert it to an object first: var jsonString = '{"some":"json"}'; var jsonPretty = JSON. stringify(JSON. parse(jsonString),null,2);
How do I beautify JSON output in Python?First of all, we are using json. loads() to create the json object from the json string.. The json. dumps() method takes the json object and returns a JSON formatted string. The indent parameter is used to define the indent level for the formatted string.. How do I print a pretty JSON file?Use pprint module to pretty-print JSON. Construct a PrettyPrinter instance first by configuring indent and width values. Also, set compact=False .. Read the JSON file using json. load() method.. Pass JSON data to pprint.pprint() function.. What is pretty print JSON?Pretty printing is a form of stylistic formatting including indentation and colouring. JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and for machines to parse and generate. The official Internet media type for JSON is application/json .
|