Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How do I extract data from a stream to specific fields

Posted on 2011-02-27
10
Medium Priority
?
598 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
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
Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

 
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 1000 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

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

This post looks at MongoDB and MySQL, and covers high-level MongoDB strengths, weaknesses, features, and uses from the perspective of an SQL user.
Creating a Cordova application which allow user to save to/load from his Dropbox account the application database.
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses

783 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