How to Pretty-Print JSON In Delphi?

10 minutes read

To pretty-print JSON in Delphi, you can make use of the JSONFormat unit from the Delphi RTL (Run-Time Library). Here's a step-by-step guide:

  1. Add the JSONFormat unit to your uses clause: uses ..., JSONFormat;
  2. Define a helper function to format the JSON: function FormatJSON(const AJSON: string): string; var S: TStringStream; Reader: TJSONTextReader; Writer: TJSONTextWriter; begin S := TStringStream.Create; Reader := TJSONTextReader.Create(AJSON); Writer := TJSONTextWriter.Create(S); try Writer.Formatting := TJsonFormatting.Indented; Writer.WriteToken(Reader); Result := S.DataString; finally S.Free; Reader.Free; Writer.Free; end; end;
  3. Now, you can pass a JSON string to the FormatJSON function to get back the pretty-printed JSON: var JSONString: string; PrettyJSON: string; begin JSONString := '{"name":"John","age":30,"city":"New York"}'; PrettyJSON := FormatJSON(JSONString); ShowMessage(PrettyJSON); end;


The FormatJSON function uses a TStringStream to store the formatted JSON and a TJSONTextWriter to write the formatted JSON to the stream. The Formatting property of TJSONTextWriter is set to TJsonFormatting.Indented to ensure an indented and easy-to-read output.


Make sure to include the necessary units and modify the code according to your specific requirements.

Best Delphi Books to Read in 2024

1
Delphi GUI Programming with FireMonkey: Unleash the full potential of the FMX framework to build exciting cross-platform apps with Embarcadero Delphi

Rating is 5 out of 5

Delphi GUI Programming with FireMonkey: Unleash the full potential of the FMX framework to build exciting cross-platform apps with Embarcadero Delphi

2
Delphi Cookbook: Recipes to master Delphi for IoT integrations, cross-platform, mobile and server-side development, 3rd Edition

Rating is 4.9 out of 5

Delphi Cookbook: Recipes to master Delphi for IoT integrations, cross-platform, mobile and server-side development, 3rd Edition

3
Mastering Pascal and Delphi Programming (Palgrave Master Series (Computing), 1)

Rating is 4.8 out of 5

Mastering Pascal and Delphi Programming (Palgrave Master Series (Computing), 1)

4
Delphi Cookbook - Second Edition

Rating is 4.7 out of 5

Delphi Cookbook - Second Edition

5
Delphi Programming Unleashed/Book and Disk

Rating is 4.6 out of 5

Delphi Programming Unleashed/Book and Disk

6
Mastering Delphi Programming: A Complete Reference Guide: Learn all about building fast, scalable, and high performing applications with Delphi

Rating is 4.5 out of 5

Mastering Delphi Programming: A Complete Reference Guide: Learn all about building fast, scalable, and high performing applications with Delphi

7
Programming and Problem Solving with Delphi

Rating is 4.4 out of 5

Programming and Problem Solving with Delphi

8
Delphi Programming for Dummies

Rating is 4.3 out of 5

Delphi Programming for Dummies

9
The Little Book Of Delphi Programming: Learn To Program with Object Pascal (Little Programming Books)

Rating is 4.2 out of 5

The Little Book Of Delphi Programming: Learn To Program with Object Pascal (Little Programming Books)


How to format JSON output in Delphi?

In Delphi, you can format JSON output using the TJsonWriter and TJsonTextWriter classes from the System.JSON unit. Here's an example of how to format JSON output in Delphi:

  1. Start by adding the System.JSON unit to your uses clause:
1
2
uses
  System.JSON;


  1. Create a TJsonWriter object and set its formatting options:
1
2
3
4
5
var
  JsonWriter: TJsonTextWriter;
begin
  JsonWriter := TJsonTextWriter.Create(YourTextWriterObject);
  JsonWriter.Formatting := TJsonFormatting.Indented; // Set the formatting style


  1. Begin writing the JSON content:
1
2
3
4
5
6
7
8
9
JsonWriter.WriteStartObject; // Start the JSON object

JsonWriter.WritePropertyName('name');
JsonWriter.WriteValue('John Doe');

JsonWriter.WritePropertyName('age');
JsonWriter.WriteValue(25);

JsonWriter.WriteEndObject; // End the JSON object


  1. Free the TJsonWriter object when you're done:
1
JsonWriter.Free;


Here's an example of the complete code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
uses
  System.JSON;

procedure FormatJsonOutput;
var
  JsonWriter: TJsonTextWriter;
begin
  JsonWriter := TJsonTextWriter.Create(YourTextWriterObject);
  JsonWriter.Formatting := TJsonFormatting.Indented;

  JsonWriter.WriteStartObject;

  JsonWriter.WritePropertyName('name');
  JsonWriter.WriteValue('John Doe');

  JsonWriter.WritePropertyName('age');
  JsonWriter.WriteValue(25);

  JsonWriter.WriteEndObject;

  JsonWriter.Free;
end;


Ensure you replace "YourTextWriterObject" with your actual output writer object, such as a TFileStream or TMemoryStream. Adjust the JSON structure accordingly to fit your needs.


By setting the Formatting property to TJsonFormatting.Indented, the JSON output will be formatted with indentation, making it more human-readable.


How to customize the indentation of JSON output in Delphi?

In Delphi, you can customize the indentation of JSON output by using the TJsonTextWriter class from the System.JSON.Writers unit. This class allows you to customize the formatting of the JSON output using various properties and methods.


Here is an example of how you can customize the indentation:

  1. Add the System.JSON.Writers unit to your uses clause to use the TJsonTextWriter class.
1
2
uses
  System.JSON.Writers;


  1. Create an instance of TJsonStringWriter to store the formatted JSON output.
1
2
3
4
var
  StringWriter: TStringWriter;
begin
  StringWriter := TStringWriter.Create;


  1. Create an instance of TJsonTextWriter and specify the indentation settings.
1
2
3
4
5
6
7
var
  JsonWriter: TJsonTextWriter;
begin
  JsonWriter := TJsonTextWriter.Create(StringWriter);
  JsonWriter.Formatting := TJsonFormatting.Indented;
  JsonWriter.IndentChar := ' ';
  JsonWriter.Indentation := 4;


In the above code, Formatting property is set to TJsonFormatting.Indented to enable indentation. IndentChar specifies the character to be used for indentation, and Indentation determines the number of indent spaces.

  1. Use TJsonTextWriter to write your JSON object or array.
1
2
3
4
5
6
JsonWriter.WriteStartObject;
JsonWriter.WritePropertyName('name');
JsonWriter.WriteValue('John Doe');
JsonWriter.WritePropertyName('age');
JsonWriter.WriteValue(30);
JsonWriter.WriteEndObject;


  1. After writing your JSON, call TJsonTextWriter.Flush to output the formatted JSON text.
1
JsonWriter.Flush;


  1. Retrieve the formatted JSON output from the TStringWriter instance.
1
2
3
4
var
  JsonOutput: string;
begin
  JsonOutput := StringWriter.ToString;


Now, JsonOutput will contain the formatted JSON with your specified indentation settings.


Remember to free the instances of TJsonTextWriter and TStringWriter after you've finished using them to avoid memory leaks.

1
2
JsonWriter.Free;
StringWriter.Free;



What is the benefit of prettifying JSON in Delphi?

Prettifying JSON in Delphi can provide several benefits:

  1. Improved readability: Prettified JSON is easier to read and understand, especially when dealing with large and complex JSON structures. It helps developers quickly grasp the structure and hierarchy of the data.
  2. Debugging and troubleshooting: When troubleshooting JSON-related issues, prettifying the JSON can help developers spot any errors or inconsistencies in the data structure and identify the root cause of the problem more easily.
  3. Collaboration and code reviews: Prettified JSON makes it simpler for multiple developers to collaborate on a project or review each other's code. It enhances communication and reduces the chances of misinterpretation.
  4. Testing and validation: Prettified JSON aids in testing and validating the correctness of the JSON data. Developers can visually compare the expected and actual JSON representations easily, ensuring the desired data transformations are occurring.
  5. Logging and logging analysis: When logging JSON data, prettifying it can enhance the readability of log files, making it easier to track and analyze the information contained within.


Overall, prettifying JSON in Delphi improves code maintainability, collaboration, troubleshooting, and understanding of complex data structures. It simplifies development and debugging processes, resulting in more efficient and reliable applications.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To parse a JSON string response using Delphi, you can use the built-in System.JSON unit that comes with Delphi. Here is a step-by-step guide on how to accomplish this:Start by adding the System.JSON unit to the uses clause of your Delphi unit. This unit contai...
If you encounter the Delphi "out of memory" error, there are a few steps you can take to try and resolve it:Check system resources: Ensure that your computer has sufficient memory available for the Delphi application to run. Close any unnecessary progr...
To access JSON data using d3.js, you can follow these steps:Load the JSON data: Use the d3.json() function to load the JSON data from a URL or a local file. For example: d3.json("data.json") .then(function(data) { // Access the JSON data here }...