1

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?

eglease
  • 2,445
  • 11
  • 18
  • 28
Skeff Igor
  • 35
  • 5
  • Are you sure that are no commas between elements? Because if there is, then it is indeed JSON and you can just [parse it as JSON](https://stackoverflow.com/q/6627652/8967612). – 41686d6564 stands w. Palestine Oct 05 '21 at 19:54
  • 3
    `+=` is not a valid assignment operator in vb6. It is in vb.net. Please correct your tags. And also - since string concatenation is being performed, `&=` and `&` would be better operators to use (though `+=` and `+` will work with the given statements). – MarkL Oct 05 '21 at 23:01
  • If you can't parse it as JSON have you looked into a regex? – StayOnTarget Oct 06 '21 at 11:25
  • If the format is fixed and can't be made into proper JOSN, then just split the string on Chr(34), and then take the 3rd, 7th, and 11th elements from the array. – Slugsie Oct 06 '21 at 12:43
  • 1
    chr(34) is a quotation mark, so the constructed string looks like `{"code":"0000001""name":"product 1""value":"150.00"}`. I doubt you'll find any existing tools that will parse that for you. Could be best to proceed as @Slugsie suggests and split the string into an array, if the string format is consistent, then the first 'value' will be the 3rd element, and any subsequent ones will be every fourth element after that (7, 11, 15, 19, etc). – MarkL Oct 06 '21 at 17:34
  • I sure hope there are no errant quotes in your data! – Idle_Mind Oct 07 '21 at 15:54

2 Answers2

2

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

Brian M Stafford
  • 8,483
  • 2
  • 16
  • 25
0

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