[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Json in Gambas


El 15/4/24 a las 09:56, Rolf-Werner Eilert escribió:
A question to everyone who has worked with Json objects in Gambas...

I inherits the Jason class and also I add a cupple of methods, maybe its will be useful to you.

' Gambas class file

Export

'' Convert a collection key value pair to csv o tsv text

Static Public Function ExportCSV(v As Variant, Optional sep As String) As String

  Dim s As String
  Dim vrt As Variant
  Dim sTag As String
  Dim sVal As String

  If sep = "" Then
    sep = "\t"
  Endif

  Select Object.Type(v)
    Case "Collection"
      For Each vrt In v
        If TypeOf(vrt) = gb.String Then
          sTag = Replace(v.Key, "\t", " ")
          sVal = Replace(vrt, "\t", " ")
          s &= sTag & sep & sVal & "\n"
        Endif
      Next
  End Select

  Return s

End

'' Encode in JSON format in a human readable way. Based on a Laurent tool.
'' Correction of brakets error By Tercoide 2022-05-1

Static Public Function Encode2(vData As Variant) As String

  Dim sInput As String
  Dim sOutput As String
  Dim iStream As Stream

  Dim $sReadChar As String
  Dim $iTab As Integer
  Dim $bQuote, $bBracket As Boolean
  Dim $BracketLevel As Integer            ' Nuevo

  sInput = JSON.Encode(vData)

  iStream = Open String sInput For Read

  While (Not Eof(iStream))
    $sReadChar = Read #iStream, 1
    If ($sReadChar = "{" And Not $bQuote) Then
      $iTab += 1
      $sReadChar &= "\n" & Space$($iTab * 2)
    Else If ($sReadChar = "}" And Not $bQuote) Then
      $iTab -= 1
      $sReadChar = "\n" & Space$($iTab * 2) & $sReadChar
    Else If ($sReadChar = "\"") Then
      $bQuote = Not $bQuote
    Else If ($sReadChar = "[") Then

      Inc $BracketLevel

      $bBracket = True

    Else If ($sReadChar = "]") Then
      $bBracket = False
      Dec $BracketLevel
    Else If ($sReadChar = ":" And Not $bQuote) Then
      $sReadChar &= " "
    Else If ($sReadChar = "," And Not $bQuote) Then

      If $BracketLevel > 1 Then             ' solo agrego un salto de linea si no hay abierto nuevos brackets
        $sReadChar &= " "
      Else
        $sReadChar &= "\n" & Space$($iTab * 2)
      End If

    Endif
    sOutput &= $sReadChar
  Wend

  Close iStream
  ' replace null with ""
  sOutput = Replace(sOutput, " null", " \"\"")

  Return sOutput

End



References:
Json in GambasRolf-Werner Eilert <rwe-sse@xxxxxxxxxx>