Home > other >  Take element from a string in VB6
Take element from a string in VB6

Time:10-09

I have a string in this format similar to the json. Generated by the following code:

str = "{"
str &= Chr(34) & "code" & Chr(34)   ":" & Chr(34) & "0000001" & Chr(34)
str &= Chr(34) & "name" & Chr(34)   ":" & Chr(34) & "product 1" & Chr(34)
str &= Chr(34) & "value" & Chr(34)   ":" & Chr(34) & "150.00" & Chr(34)
str &= "}"

I just need to get the value after the code, name and value. I cannot find an effective method to do this, as I will have to generalize to more terms later. How can I do this without transforming to JSON?

CodePudding user response:

The code snippet you provide produces this string:

{"code":"0000001""name":"product 1""value":"150.00"}

Assuming you really are using VB6 to process this string, the following code breaks out the values:

Private Sub Test(ByVal str As String)
   Dim groups As Variant
   Dim values As Variant
   Dim i As Integer

   str = Replace(str, "{", "")
   str = Replace(str, "}", "")
   str = Replace(str, """""", ",")
   str = Replace(str, """", "")
   groups = Split(str, ",")

   For i = LBound(groups) To UBound(groups)
      values = Split(groups(i), ":")
      Debug.Print values(1)
   Next
End Sub

enter image description here

CodePudding user response:

Something like this should help (untested):


colon% = 0
Dim completed as Boolean

while completed = false
colon% = InStr(colon%   1, str, ":") 
If colon% > 0 Then
value$ = Mid$(str, colon   1, InStr(colon%   2, str, Chr(34)) - colon%) 
' ... do whatever with value$ here...
Else
completed = true
End If

Wend

  • Related