VBA-tools / VBA-JSON

JSON conversion and parsing for VBA
MIT License
1.74k stars 565 forks source link

Fix line feed character parsing in multiline value #253

Open joyfullservice opened 1 year ago

joyfullservice commented 1 year ago

I know this has been discussed in the following issues:

As a simple matter of principle, JSON conversion should be converting, not changing the original string. A proper conversion should support a round-trip conversion back to the original value. This can be demonstrated with the following code snippet:

'---------------------------------------------------------------------------------------
' Procedure : TestJsonNewLineIssue
' Author    : Adam Waller
' Date      : 7/24/2023
' Purpose   : Encountered an issue where vbCrLf strings are not parsed correctly when
'           : converting to JSON and back to string values.
'---------------------------------------------------------------------------------------
'
Public Sub TestJsonNewLineIssue()

    Const cstrTest As String = "Line1" & vbCrLf & "Line2" & vbCr & "Line3" & vbLf & "Line4" & vbCrLf

    Dim dTest As Dictionary
    Dim strResult As String

    Set dTest = New Dictionary

    dTest("Multiline") = cstrTest
    Debug.Assert dTest("Multiline") = cstrTest

    ' Test round trip conversion
    strResult = ParseJson(ConvertToJson(dTest, 2))("Multiline")
    Debug.Assert (strResult = cstrTest)

End Sub

Replacing a line feed (vbLf) single character, with two characters (vbCrLf) may be necessary in some applications, but this should be performed in the calling code, not embedded within the JSON conversion. In my opinion, the JSON conversion should only be performing the conversion. What goes in is what should come out. 😄

On the VBA side, vbCrLf = (vbCr & vbLf) so I don't know that we need to do anything more complicated than simply converting \n to vbLf.