How do I extract data from a stream to specific fields

I have a program that queries a web URL and returns the data that is currently displayed in a label. The raw data is in the form of:

  "field_1":"Result_text",
  "field_2":"Result_text",
  "Field_3":"Result_text",
for a total of 14 lines. Every query will always be formatted the same, with the results different.

I'm reading the result using:

Dim stream_reader As New IO.StreamReader(response)
 Label1.Text = stream_reader.ReadToEnd()

I'm looking to extract the "Result_Text" to populate different labels.

Any help would be greatly appreciated.
dschreffAsked:
Who is Participating?
 
DhaestCommented:
I tried it with your example ...

        Dim responseString As String = "geoPlugin({"
        responseString += """geoplugin_city"":""city"","
        responseString += """geoplugin_region"":""state"","
        responseString += """geoplugin_areaCode"":""570"","
        responseString += """geoplugin_dmaCode"":""574"","
        responseString += """geoplugin_countryCode"":""US"","
        responseString += """geoplugin_countryName"":""United States"","
        responseString += """geoplugin_continentCode"":""NA"","
        responseString += """geoplugin_latitude"":""40.791199"","
        responseString += """geoplugin_longitude"":""-77.874603"","
        responseString += """geoplugin_regionCode"":""PA"","
        responseString += """geoplugin_regionName"":""Pennsylvania"","
        responseString += """geoplugin_currencyCode"":""USD"","
        responseString += """geoplugin_currencySymbol"":""$"","
        responseString += """geoplugin_currencyConverter"":1"
        responseString += "})"

Dim stream_reader As New IO.StreamReader(response)
dim responseString as string = stream_reader.ReadToEnd()


        responseString = responseString.Substring(responseString.IndexOf("{") + 1, responseString.IndexOf("}") - responseString.IndexOf("{") - 1)
        Dim splitResponse As String() = responseString.Replace("""", "").Split(",")


        Dim i As Integer

        For i = 0 To 14
            Me.Controls("label" & i + 1).Text = splitResponse(i).Split(":")(1)
        Next i

Open in new window

0
 
bansidharCommented:
try this. not much error handling is implemented

Private Function getFieldValue(ByVal ReceivedString As String) As Dictionary(Of String, String)
        Dim fieldValues As New Dictionary(Of String, String)
        Dim lst() As String = ReceivedString.Split(",")
        For i As Integer = 0 To lst.Length - 1
            Dim fvstr As String = lst(i).Trim
            If fvstr <> "" Then
                Dim fv() As String = fvstr.Split(":")
                Dim field As String = fv(0).Trim("""")
                If fieldValues.ContainsKey(field) Then fieldValues.Item(field) = fv(1).Trim("""") Else fieldValues.Add(field, fv(1).Trim(""""))
            End If
        Next
        Return fieldValues
    End Function

Open in new window

0
 
robastaCommented:
data = stream_reader.ReadToEnd()
            string[] arr = data.Split(',');
            string[] labelText = new string[13];//use number of fields
            int i = 0;
           
            foreach (string item in arr)
            {
                string[] itemArr = item.Split(':');
                labelText[i]  = itemArr[0].Replace('"', ' ').Trim();
                i++;
            }


            Label1.Text = labelText[0];
            Label2.Text = labelText[1];
            Label3.Text = labelText[2];
            Label4.Text = labelText[3];
            //etc.

Open in new window




-you may need to


0
Improve Your Query Performance Tuning

In this FREE six-day email course, you'll learn from Janis Griffin, Database Performance Evangelist. She'll teach 12 steps that you can use to optimize your queries as much as possible and see measurable results in your work. Get started today!

 
robastaCommented:
ooopsy, ive converted to VB:
data = stream_reader.ReadToEnd()
Dim arr As String() = data.Split(","C)
Dim labelText As String() = New String(12) {}
'use number of fields
Dim i As Integer = 0

For Each item As String In arr
	Dim itemArr As String() = item.Split(":"C)
	labelText(i) = itemArr(0).Replace(""""C, " "C).Trim()
	i += 1
Next


Label1.Text = labelText(0)
Label2.Text = labelText(1)
Label3.Text = labelText(2)
Label4.Text = labelText(3)
'etc.

Open in new window

0
 
DhaestCommented:
So I assume that you have everything read into a string and that you want everything into a label (which are numbered)



Dim stream_reader As New IO.StreamReader(response)
dim responseString as string = stream_reader.ReadToEnd()


        Dim splitResponse As String() = responseString.Replace(",", "").Replace("""", "").Split(vbCrLf)

        Dim i As Integer

        For i = 0 To 14
            Me.Controls("label" & i + 1).Text = splitResponse(i).Split(":")(1)
        Next i

Open in new window

0
 
dschreffAuthor Commented:
I am using the code from Dhaest, but am having a problem. When executed, it gives the error of "index was outside the bounds of the array". I think it may be caused by an addition of a line to the data that is being grabbed. It not looks like this:

127.0.0.1 ({
  "field_1":"Result_text",
  "field_2":"Result_text",
  "Field_3":"Result_text",

When executed, My result shows 127.0.0.1({ Result_text where I just want the "result_text".

Thanks again for your help
0
 
DhaestCommented:
Can you post the complete string that you retrieved, because I worked with the following (see below):
But you're string is something bigger

Perhaps you just want to start after {

try the following:

Dim stream_reader As New IO.StreamReader(response)
dim responseString as string = stream_reader.ReadToEnd()

responseString = responseString.Substring(responseString.IndexOf("{") + 1)
Dim responseString = """field_1"":""Result_text"",""" & vbCrLf
        responseString += """field_2"":""Result_text"",""" & vbCrLf
        responseString += """field_3"":""Result_text"",""" & vbCrLf
        responseString += """field_4"":""Result_text"",""" & vbCrLf
        responseString += """field_5"":""Result_text"",""" & vbCrLf
        responseString += """field_6"":""Result_text"",""" & vbCrLf
        responseString += """field_7"":""Result_text"",""" & vbCrLf
        responseString += """field_8"":""Result_text"",""" & vbCrLf
        responseString += """field_9"":""Result_text"",""" & vbCrLf
        responseString += """field_10"":""Result_text"",""" & vbCrLf
        responseString += """field_11"":""Result_text"",""" & vbCrLf
        responseString += """field_12"":""Result_text"",""" & vbCrLf
        responseString += """field_13"":""Result_text"",""" & vbCrLf
        responseString += """field_14"":""Result_text"","""

Open in new window

0
 
dschreffAuthor Commented:
The string received shows IP address location. For something that should be straight forward I'm pulling out what hair I have. I just want to show the results (i.e. city state etc) as labels so it's clean on the form.

geoPlugin({
  "geoplugin_city":"city",
  "geoplugin_region":"state",
  "geoplugin_areaCode":"570",
  "geoplugin_dmaCode":"574",
  "geoplugin_countryCode":"US",
  "geoplugin_countryName":"United States",
  "geoplugin_continentCode":"NA",
  "geoplugin_latitude":"40.791199",
  "geoplugin_longitude":"-77.874603",
  "geoplugin_regionCode":"PA",
  "geoplugin_regionName":"Pennsylvania",
  "geoplugin_currencyCode":"USD",
  "geoplugin_currencySymbol":"&#36;",
  "geoplugin_currencyConverter":1
})

0
 
bansidharCommented:
try this, you will get a dictionary populated

Private Function getParsedData(ByVal stringData As String) As Dictionary(Of String, String)
        Dim dict As New Dictionary(Of String, String)
        Dim mm As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(stringData, "\({(.*)}\)", System.Text.RegularExpressions.RegexOptions.Singleline)
        If mm.Success Then
            Dim m() As String = System.Text.RegularExpressions.Regex.Split(stringData, "\({(.*)}\)", System.Text.RegularExpressions.RegexOptions.Singleline)
            Dim v() As String = System.Text.RegularExpressions.Regex.Split(m(1).Trim, "(""[^""]*"":""?[^""]*""?)", System.Text.RegularExpressions.RegexOptions.Singleline)
            For i As Integer = 0 To v.Length - 1
                If v(i).Trim(",").Trim <> "" Then
                    Dim fv() As String = v(i).Split(":")    'Just to avoid out of index for items without values
                    ReDim Preserve fv(1)
                    Dim _key As String = fv(0).Trim("""")
                    Dim _val As String = fv(1).Trim("""")
                    If dict.ContainsKey(_key) Then dict.Item(_key) = _val Else dict.Add(_key, _val)
                End If
            Next
        End If
        Return dict
    End Function

Open in new window

0
 
dschreffAuthor Commented:
Just what I needed, thank you!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.