Pretty format json?

lock
push_pin
done
Besvaret
6

Is it possible to pretty format a json string: Map m = Map(data); printLine(m.toJson());

Outputs: { "First": "Martin", "Last": "Andersen"}

I would like to have it like this:

{
  "First": "Martin",
  "Last": "Andersen"
}
 
Regards Martin

10. jul. 2026 | 10.54 AM

Alle Svar (6)

Not by default, but you can use the code shared by Sverre here: Simple JSON formatter in CRMScript

10. jul. 2026 | 11.05 AM

OK, that is good! Thank you!

10. jul. 2026 | 11.08 AM

Hi Martin, this should work:

#setLanguageLevel 4;

Map data;
data.insert("First", "Martin");
data.insert("Last", "Andersen");

printLine(parseJSON2(data.toJson()).toJSON(2));
20. jul. 2026 | 06.44 AM

Very nice, two options. One is a custom function which can be changed to suit your needs. The other is inbuilt and most likely much faster, but it needs to convert to XML and as such duplicate your data and use a lot of lists to make the xml manageable internally, and it will use a lot of memory. But if you have memory left, this will be faster and you don’t need to define a method.

Thank you both.

20. jul. 2026 | 07.55 AM

Can I ask in what context are you going to use the formatted JSON?

In addition to those solutions mentioned above, depending on your use - there are other options.


You have webpages such as jsonlint.com which will validate and format your JSON string:

This of course requires you to copy / paste the output, which may be a hassle if it's a large string.

If you're having a panel where you want to display it formatted, you can use jQuery libraries for that purpose.

3. aug. 2026 | 06.40 AM

It is for output to an email send when an error occurs in a larger system, the email is send from a script and will contain a payload from an external system calling into a script. The email is not meant for users but for an administrator, and the prettyPrint will make it much easier to read.

6. aug. 2026 | 07.33 AM

Tilføj svar