Solved

How do I extract data from a stream to specific fields

Posted on 2011-02-27
10
535 Views
Last Modified: 2013-11-15
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.
0
Comment
Question by:dschreff
  • 3
  • 3
  • 2
  • +1
10 Comments
 
LVL 11

Expert Comment

by:bansidhar
Comment Utility
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
 
LVL 14

Expert Comment

by:robasta
Comment Utility
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
 
LVL 14

Expert Comment

by:robasta
Comment Utility
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
 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
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
 

Author Comment

by:dschreff
Comment Utility
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 53

Expert Comment

by:Dhaest
Comment Utility
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
 

Author Comment

by:dschreff
Comment Utility
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
 
LVL 11

Expert Comment

by:bansidhar
Comment Utility
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
 
LVL 53

Accepted Solution

by:
Dhaest earned 250 total points
Comment Utility
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"":""&#36;"","
        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
 

Author Closing Comment

by:dschreff
Comment Utility
Just what I needed, thank you!
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now