Solved

How do I extract data from a stream to specific fields

Posted on 2011-02-27
10
587 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
  • +1
10 Comments
 
LVL 11

Expert Comment

by:bansidhar
ID: 34994903
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
ID: 34994930
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
ID: 34994944
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
MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

 
LVL 53

Expert Comment

by:Dhaest
ID: 34994964
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
ID: 35000715
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
 
LVL 53

Expert Comment

by:Dhaest
ID: 35004623
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
ID: 35012178
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
ID: 35014495
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
ID: 35014845
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
ID: 35015165
Just what I needed, thank you!
0

Featured Post

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Shadow IT is coming out of the shadows as more businesses are choosing cloud-based applications. It is now a multi-cloud world for most organizations. Simultaneously, most businesses have yet to consolidate with one cloud provider or define an offic…
Recently I was talking with Tim Sharp, one of my colleagues from our Technical Account Manager team about MongoDB’s scalability. While doing some quick training with some of the Percona team, Tim brought something to my attention...
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…

734 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