Pretty-Print JSON in Java

Google’s GSON can do this in a nice way: Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(uglyJsonString); String prettyJsonString = gson.toJson(je); or since it is now recommended to use the static parse method from JsonParser you can also use this instead: Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonElement je = … Read more

How to turn off the Eclipse code formatter for certain sections of Java code?

Eclipse 3.6 allows you to turn off formatting by placing a special comment, like // @formatter:off … // @formatter:on The on/off features have to be turned “on” in Eclipse preferences: Java > Code Style > Formatter. Click on Edit, Off/On Tags, enable Enable Off/On tags. It’s also possible to change the magic strings in the … Read more

How to pretty-print a numpy.array without scientific notation and with given precision?

You can use set_printoptions to set the precision of the output: import numpy as np x=np.random.random(10) print(x) # [ 0.07837821 0.48002108 0.41274116 0.82993414 0.77610352 0.1023732 # 0.51303098 0.4617183 0.33487207 0.71162095] np.set_printoptions(precision=3) print(x) # [ 0.078 0.48 0.413 0.83 0.776 0.102 0.513 0.462 0.335 0.712] And suppress suppresses the use of scientific notation for small numbers: … Read more

How to prettyprint a JSON file?

The json module already implements some basic pretty printing in the dump and dumps functions, with the indent parameter that specifies how many spaces to indent by: >>> import json >>> >>> your_json = ‘[“foo”, {“bar”:[“baz”, null, 1.0, 2]}]’ >>> parsed = json.loads(your_json) >>> print(json.dumps(parsed, indent=4, sort_keys=True)) [ “foo”, { “bar”: [ “baz”, null, 1.0, … Read more