Read data from JSON file, add new data following data structure VB.NET - vb.net

Okay, So I have been trying to wrap my small head around this topic for some time now. All I want to do is:
1) Read all data from a .json file
2) Add data to the json file, while still following structure (Adding objects withing java somehow maybe?)
3) Save file back
I have figured out how to download json.net and add it to my project. I just have no clue how to use it.
I am a big noob at java and vb, so please don't reply with a bunch of unnecessary stuff that won't help. (Really irritated by this already :|)
I am writing this with a GUI, so no console stuff, as I seen from most of the sources on the interweb.
Things I have tried: Reading all lines and storing into var, array and or string.
Dim str() As String = IO.File.ReadAllLines("C:\MCHCI_Profile.txt")
I got this from somewhere but threw and error of 1 dimensional array
Dim singleChar As Char
singleChar = str.Chars(14)
Somethings with streamreader and writer but not too much, as it confuses me.
Using sr As StreamReader = New StreamReader("C:\MCHCI_Profile.txt")
Do
ListBox1.Items.Add(sr.ReadLine())
Loop Until sr.EndOfStream
End Using
^This seemed to work, it added all the right data into combobox and kept json structure, but I don't know what to do with it.
Final conclusion
It seems like the only real way to do this is with json.net
So please let me know how to read data, add simple objects to it and save it back
Thank you !!!

As of now i don't get what actually you are trying to achieve. Let me assume that
1. You are accepting a text file content to a one dimensional array.
2. then you are selecting a single character from particular index from that array, isn't it?
this will achieve the first option without fail.
Dim str() As String = File.ReadAllLines("D:\sample.txt")
if you want particular line of text then you can take it from the array by using the index value as like the following:
Dim lineOfText As String = str(14)
if you want a single character from particular line of text then you can take it from the array by using the index value as like the following:
Dim singleChar As Char=str(14).ToCharArray()(2)

Related

Match Words and Add Quantities vb.net

I am trying to program a way to read a text file and match all the values and their quantites. For example if the text file is like this:
Bread-10 Flour-2 Orange-2 Bread-3
I want to create a list with the total quantity of all the common words. I began my code, but I am having trouble understanding to to sum the values. I'm not asking for anyone to write the code for me but I am having trouble finding resources. I have the following code:
Dim query = From data In IO.File.ReadAllLines("C:\User\Desktop\doc.txt")
Let name As String = data.Split("-")(0)
Let quantity As Integer = CInt(data.Split("-")(1))
Let sum As Integer = 0
For i As Integer = 0 To query.Count - 1
For j As Integer = i To
Next
Thanks
Ok, lets break this down. And I not seen the LET command used for a long time (back in the GWBASIC days!).
But, that's ok.
So, first up, we going to assume your text file is like this:
Bread-10
Flour-2
Orange-2
Bread-3
As opposed to this:
Bread-10 Flour-2 Orange-2 Bread-3
Now, we could read one line, and then process the information. Or we can read all lines of text, and THEN process the data. If the file is not huge (say a few 100 lines), then performance is not much of a issue, so lets just read in the whole file in one shot (and your code also had this idea).
Your start code is good. So, lets keep it (well ok, very close).
A few things:
We don't need the LET for assignment. While older BASIC languages had this, and vb.net still supports this? We don't need it. (but you will see examples of that still floating around in vb.net - especially for what we call "class" module code, or "custom classes". But again lets just leave that for another day.
Now the next part? We could start building up a array, look for the existing value, and then add it. However, this would require a few extra arrays, and a few extra loops.
However, in .net land, we have a cool thing called a dictionary.
And that's just a fancy term of for a collection VERY much like an array, but it has some extra "fancy" features. The fancy feature is that it allows one to put into the handly list things by a "key" name, and then pull that "value" out by the key.
This saves us a good number of extra looping type of code.
And it also means we don't need a array for the results.
This key system is ALSO very fast (behind the scene it uses some cool concepts - hash coding).
So, our code to do this would look like this:
Note I could have saved a few lines here or there - but that would make this code hard to read.
Given that you look to have Fortran, or older BASIC language experience, then lets try to keep the code style somewhat similar. it is stunning that vb.net seems to consume even 40 year old GWBASIC type of syntax here.
Do note that arrays() in vb.net do have some fancy "find" options, but the dictionary structure is even nicer. It also means we can often traverse the results with out say needing a for i = 1 to end of array, and having to pull out values that way.
We can use for each.
So this would work:
Dim MyData() As String ' an array() of strings - one line per array
MyData = File.ReadAllLines("c:\test5\doc.txt") ' read each line to array()
Dim colSums As New Dictionary(Of String, Integer) ' to hold our values and sum them
Dim sKey As String
Dim sValue As Integer
For Each strLine As String In MyData
sKey = Split(strLine, "-")(0)
sValue = Split(strLine, "-")(1)
If colSums.ContainsKey(sKey) Then
colSums(sKey) = colSums(sKey) + sValue
Else
colSums.Add(sKey, sValue)
End If
Next
' display results
Dim KeyPair As KeyValuePair(Of String, Integer)
For Each KeyPair In colSums
Debug.Print(KeyPair.Key & " = " & KeyPair.Value)
Next
The above results in this output in the debug window:
Bread = 13
Flour = 2
Orange = 2
I was tempted here to write this code using just pure array() in vb.net, as that would give you a good idea of the "older" types of coding and syntax we could use here, and a approach that harks all the way back to those older PC basic systems.
While the dictionary feature is more advanced, it is worth the learning curve here, and it makes this problem a lot easier. I mean, if this was for a longer list? Then I would start to consider introduction of some kind of data base system.
However, without some data system, then the dictionary feature is a welcome approach due to that "key" value lookup ability, and not having to loop. It also a very high speed system, so the result is not much looping code, and better yet we write less code.

CSV Data handling - vb.net

I've been asked at work to create a project to open a CSV and then use a set of conditions to change and save the data using Visual Basic.net (2010)
Although I am comfortable creating files in vb and opening them again into vb, I don't know how to declare the fields so I can query them. For example:
if field1 = "Yes" and field2 = "Blue" then textbox1.text = "abcd"
Then at a later stage I want to export a file which I'm happy doing where it writes lines to create a new CSV which could be Field1, textbox1.text, Field3 and so on
Also, would I have to declare line1.field1 and line2.field1 or could I declare line2.field1 as field25 for example or whatever the next sequential number may be?
Thanks
How are you going to read from the file?
If you do File.ReadAllLines
what does it return? A string array.
Does a string array have properties like line1? No, but they do have indexers.
How do you access an element in a string array? With a indexer,
e.g. array(0).
Does an string have properties like field1? Nope.
Can you use String.Split to split on the commas and separate the fields? Yes.
Could you write a class that has specific properties defined for each field that has a constructor that'd take a string that represents a row and put the value into the correct fields? Yes.
Could the same class know how to convert itself into a single CSV style line? Yup.
Are there other library that could help you do this? Probably.
All that being said, you can probably get away with doing something simple like this (warning: naive code sample):
Dim fileName = "C:\testFile.csv"
Dim lines = File.ReadAllLines(fileName)
Dim output As New List(Of String)
For Each line In lines
Dim fields = line.Split(","c)
fields(0) = "000" 'Blank out number
If fields(3) = "Y" Then 'Change Y to True
fields(3) = "True"
End If
output.Add(String.Join(","c, fields))
Next
File.WriteAllLines(fileName, output)
I gave it input that looked like this:
123,abc,Y,Y,N
456,def,Y,N,Y
789,ghi,N,Y,Y
012,jkl,N,N,N
and it changed the file to this:
000,abc,Y,True,N
000,def,Y,N,Y
000,ghi,N,True,Y
000,jkl,N,N,N
Utilities for working with CSV will do a better job than this. There are various ways this won't work (doesn't handle any escape sequences, etc.) but this could be sufficient if you're just wanting to do something quick and dirty and don't need to worry about some things. At the very least hopefully it'll give you a better understanding of how you'd go about solving a problem like this.
I'd recommend writing the output to a different file to test.

Grabbing sections of a text file - vb

Probably kick-self simple, but this is defeating me.
I have a text file which I am looking to grab in sections and populates separate text boxes. This is what the list looks like:
data_file_name
<1st section>
data
data
data
<2nd section>
data
data
data
etc.
Is there a way for me to take each section? I thought of changing the delimiter in a TextReader but some of the data also has the <> signs in it.
One way is to use system.io.file.readalllines(path) to read the file into a string array. Then process the array in memory sequentially, or using indexof, for "<1st section>", etc. This one approach of about a dozen that will work equally well.
Below is code to read each line of the file into a string. Then, you compare the string value to see if it looks like a new section. If so, do your new section code, else to your current section code
Dim reader as new streamreader(file.txt)
Dim inline as String
While reader.peek <> -1
inline = reader.readline
if inline.startswith("<") and inline.endswith(">") and inline.contains("section")
'do new section routine
else
'do current section routine
end if
end while
reader.close

How do you input all txt files in a directory into an array?

I want to know how you put all the txt files within a folder into array, also if possible--> I'm anticipating the numbers of files to change so please consider a dynamic array or just simply copying and pasting into another array that fits all elements(file names in this case) into that array .this is so I manipulate the order of elements(files in this case)
I searched through other questions with C# tag but since i'm new i can't understand or translate concept into vb.
Try this:
using System.IO;
...
string[] dirs = Directory.GetFiles(#"c:\", "*.txt");
Cheers
EDIT oops... I keep getting bitten by this. Answering C# to VB.NET tagged questions.
VB.NET:
Dim dirs As String() = Directory.GetFiles("c:\", "*.txt")

Using streamreader I can read the next line of words, but can I read the previous one?

Can I read the previous line using StreamReader?
Dim previousfile As New StreamReader("file.txt")
If previousfile.Peek <> +1 Then
txtName.text = previousfile.ReadLine
End If
Can anyone help?
you cannot read the previous line - StreamReader really is a forward only type of reader. when you read a line... thats it. you cannot go back.
why dont you hold the previous line being read in a temp variable or maybe use the FileStream which has a Seek method which maybe of some use to you?
or why not read the entire contents into a collection of strings and splitting it on some delimeter for example?
You can't read backwards with a StreamReader, but if you read all of the lines in first you can traverse them however you like. This does mean reading the whole file in up front, which may be less efficient depending on your usage, but this method would do the job and give you an array:
var lines = File.ReadAllLines("file.txt")