Skip to content

Instantly share code, notes, and snippets.

@willyhorizont
Last active March 10, 2024 13:30
Show Gist options
  • Save willyhorizont/ca825ee3a83057b036765f2d3a18eabe to your computer and use it in GitHub Desktop.
Save willyhorizont/ca825ee3a83057b036765f2d3a18eabe to your computer and use it in GitHub Desktop.
Pretty Print | Pretty JSON Stringify in Visual Basic (.NET)
Imports System.Collections.Generic ' Dictionary, KeyValuePair
Module Program
Function PrettyJsonStringify(ByVal Anything As Object, Optional ByVal Indent As String = " ") As String
Dim IndentLevel As Integer = 0
Dim PrettyJsonStringifyInner As Func(Of Object, String, String) = Function(ByVal AnythingInner As Object, ByVal IndentInner As String)
If (AnythingInner Is Nothing) Then Return "null"
If (TypeOf AnythingInner Is String) Then Return """" & AnythingInner & """"
If (IsNumeric(AnythingInner) OrElse (TypeOf AnythingInner Is Boolean)) Then Return CStr(AnythingInner)
If (TypeOf AnythingInner Is List(Of Object)) Then
If (AnythingInner.Count = 0) Then Return "[]"
IndentLevel += 1
Dim Result As String = "[" & Environment.NewLine & String.Concat(Enumerable.Repeat(IndentInner, IndentLevel))
Dim ArrayItemIndex As Integer = 0
For Each ArrayItem As Object In AnythingInner
Result &= PrettyJsonStringifyInner(ArrayItem, IndentInner)
If ((ArrayItemIndex + 1) <> AnythingInner.Count) Then Result &= "," & Environment.NewLine & String.Concat(Enumerable.Repeat(IndentInner, IndentLevel))
ArrayItemIndex += 1
Next
IndentLevel -= 1
Result &= Environment.NewLine & String.Concat(Enumerable.Repeat(IndentInner, IndentLevel)) & "]"
Return Result
End If
If (TypeOf AnythingInner Is Dictionary(Of String, Object)) Then
If (AnythingInner.Count = 0) Then Return "{}"
IndentLevel += 1
Dim Result As String = "{" & Environment.NewLine & String.Concat(Enumerable.Repeat(IndentInner, IndentLevel))
Dim IterationIndex As Integer = 0
For Each ObjectEntry As KeyValuePair(Of String, Object) In AnythingInner
Dim ObjectKey = ObjectEntry.Key
Dim ObjectValue = ObjectEntry.Value
Result &= """" & ObjectKey & """: " & PrettyJsonStringifyInner(ObjectValue, IndentInner)
If ((IterationIndex + 1) <> AnythingInner.Count) Then Result &= "," & Environment.NewLine & String.Concat(Enumerable.Repeat(IndentInner, IndentLevel))
IterationIndex += 1
Next
IndentLevel -= 1
Result &= Environment.NewLine & String.Concat(Enumerable.Repeat(IndentInner, IndentLevel)) & "}"
Return Result
End If
Return "null"
End Function
Return PrettyJsonStringifyInner(Anything, Indent)
End Function
Sub Main(Args As String())
Dim Products As List(Of Object) = New List(Of Object) From {
New Dictionary(Of String, Object) From {
{"id", "P1"},
{"name", "bubble gum"}
},
New Dictionary(Of String, Object) From {
{"id", "P2"},
{"name", "potato chips"}
}
}
Console.WriteLine("Products: " & PrettyJsonStringify(Products))
End Sub
End Module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment