How can I extract these key/value pairs from this JSON node? - c#

I've been successfully using JToken and JArray to grab specific pieces of data, but I'm having one particular issue. The issues lie with extracting the values from the key/value pairs in my node 'work_unit.' You can see the node here in my JObject:
JObject testString = JObject.Parse("{"
+ "'Roofing': {"
+ "'Buildings': ["
+ "{"
+ "'BuildingId': 4,"
+ "'BuildingName': 'what',"
+ "'work_unit': '{\"RoofingBuildings\":\"1\",\"WindowsBuildings\":\"\",\"GutterBuildings\":\"\",\"InsulationMasterPrice\":\"\",\"SidingBuildings\":\"\"}'"
+ "},"
+ "{"
+ "'BuildingId': 3,"
+ "'BuildingName': 'Home'"
+ "}"
+ "],"
+ "'Windows': ["
+ "{"
+ "'PerimeterDrawings': 56,"
+ "},"
+ "{"
+ "'PerimeterDrawings': 55,"
+ "}"
+ "]"
+ "},"
+ "'Window':"
+ "{"
+ "'poof': 3,"
+ "'stall': 7"
+ "},"
+ "'Products': ["
+ "'Roofing',"
+ "'Pooping',"
+ "],"
+ "'Garage': ["
+ "{"
+ "'roof': 3,"
+ "'wall': 7"
+ "},"
+ "{"
+ "'roof': 3,"
+ "'wall': 7"
+ "}"
+ "]"
+ "}");
I can get the entirety of 'work_unit' like so:
JToken jt= JO.SelectToken("Roofing.Buildings[0].work_unit");
^^ jt will contain:
{{"RoofingBuildings":"1","WindowsBuildings":"","GutterBuildings":"","InsulationMasterPrice":"","SidingBuildings":""}}
How do I get the "1" from RoofingBuildings? I've tried several methods, here are some, but they just end up being null.
string foo1 = (string)JTNewTest.SelectToken(".RoofingBuildings");
string foo2 = (string)JO.SelectToken("Roofing.Buildings[0].work_unit[0].RoofingBuildings");
Thanks in advance, I couldn't find my exact situation in any other online examples for some reason :/

You can get it like this, I assumed that the work_unit was supposed to be split up into it's own properties rather than being a string.. Hopefully I was correct in that assumption. Also made multi-line string for readability sake.
JObject testString = JObject.Parse(#"
{
'Roofing': {
'Buildings':
[
{
'BuildingId': 4,
'BuildingName': 'what',
'work_unit':
{
'RoofingBuildings':'1',
'WindowsBuildings':'',
'GutterBuildings':'',
'InsulationMasterPrice':'',
'SidingBuildings':''
}
},
{
'BuildingId': 3,
'BuildingName': 'Home'
}
],
'Windows':
[
{
'PerimeterDrawings': 56,
},
{
'PerimeterDrawings': 55,
}
]
},
'Window':
{
'poof': 3,
'stall': 7
},
'Products':
[
'Roofing',
'Pooping'
],
'Garage':
[
{
'roof': 3,
'wall': 7
},
{
'roof': 3,
'wall': 7
}
]
}");
var roofingBuildings = testString["Roofing"]["Buildings"][0]["work_unit"]["RoofingBuildings"];
Console.WriteLine("RoofingBuildings: {0}", roofingBuildings);

Related

How to replace word with hyperlink?

Starting with an example, I have some keywords like
Narendra Modi, Modi, India, Speech, Parliament
And I have a story with text
Narendra Modi will give a speech in the parliament of India.
Now I want my regex to replace the keyword with the hyperlink in the story.
<a>Narendra Modi</a> will give speech in the <a>parliament</a> of <a>India.</a>
My Code for this is
var tagArray = bodykeywords.Split(',').ToList();
foreach (var tag in tagArray.OrderBy(a => a.Length))
{
var replaceTag = tag.Replace("(", "");
replaceTag = replaceTag.Replace(")", "");
DataDesc = Regex.Replace(DataDesc, "\"" + replaceTag.Trim() + "\"", " \"" + replaceTag.Trim() + "\" ");
DataDesc = Regex.Replace(DataDesc, " " + replaceTag.Trim() + ", ", " " + replaceTag.Trim() + ", ");
DataDesc = Regex.Replace(DataDesc, " " + replaceTag.Trim() + " ", " " + replaceTag.Trim() + " ");
}
Problem is I am not able to replace the word with full stop like India in the given example and Word with repetition like Narendra Modi, Modi in the keyword.

How can I successfully extract this substring in C#?

Here is the offending code. I haven't done much string manipulation yet, and am currently having issues.
if (orderid != orderlist[orderlist.Count - 1])
{
response2 = GetSubstringByString("{\"orderid\": \"" + orderid + "\"", "{\"orderid\": \"", response2);
}
else
{
response2 = GetSubstringByString("{\"orderid\": \"" + orderid + "\"", "success", response2);
}
Console.WriteLine("Response 2 is: " + response2);
logger.Log("Writing " + writepath + filename);
File.WriteAllText(writepath + filename, response2);
}
public string GetSubstringByString(string a, string b, string c) //trims beginning and ending of string
{
Console.WriteLine("String a is: " + a + "String b is: " + b + "String c is: " + c);
return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b) - c.IndexOf(a) - a.Length));
}
I am having issues extracting a substring, as the beginning and ending strings are the same, and therefore it is unable to differentiate the strings from each other.
Here is the main issue:
response2 = GetSubstringByString("{\"orderid\": \"" + orderid + "\"", "{\"orderid\": \"", response2);
Is there a way I can add a check if the orderid for the ending string differs from the starting string orderid? Thanks for any help!
I was working with code that was already set to scan rather than parse JSON in the optimal fashion.
I utilized this regex to remove orderid before each number as to not cause scanner length exceptions. I also overloaded string.IndexOf as mentioned by juharr.
var regex = new Regex(Regex.Escape("orderid")); //replace first occurrence of orderid
response2 = regex.Replace(response2, "", parsecount-1);
public string GetSubstringByString(string a, string b, string c) //trims beginning and ending of string
{
logger.Log("String a is: " + a + "String b is: " + b + "String c is: " + c);
var offset = c.IndexOf(b);
//lastcheck will return 0 if it's last element in orderlist, because ending string differs for last
return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b, offset + lastcheck) - c.IndexOf(a) - a.Length));
}

Regular expression getting html between two comments

I am trying to get a snippet of HTML between to comments.
I will need to parse the HTML between the start/end later.
I am actually reading from an html file but for test purposes I mocked the following up:
string emailFeedTxtStart = "<!--FEED FOR RECEIPT GOES HERE-->";
string emailFeedTxtEnd = "<!--FEED FOR RECEIPT ENDS HERE-->";
string html =
emailFeedTxtStart + Environment.NewLine +
#"<td align=""center"">" + Environment.NewLine +
#"<table style=""table-layout:fixed;width:380px"" border=""0"" cellspacing=""0"" cellpadding=""0"">" + Environment.NewLine +
"<tbody>" + Environment.NewLine +
"<tr>" + Environment.NewLine +
"<td>" + Environment.NewLine +
"</td>" + Environment.NewLine +
"</tr>" + Environment.NewLine +
"</tbody>" + Environment.NewLine +
"</table>" + Environment.NewLine +
"</td>" + Environment.NewLine +
emailFeedTxtEnd;
string patternstart = Regex.Escape(emailFeedTxtStart);
string patternend = Regex.Escape(emailFeedTxtEnd);
string regexexpr = patternstart + #"(.*?)" + patternend;
//string regexexpr = #"(?<=" + patternstart + ")(.*?)(?=" + patternend + ")";
MatchCollection matches = Regex.Matches(#html, #regexexpr);
matches returned is 0.
(note there is a lot more HTML between the ).
Any help would be greatly appreciated.
What are you going to parse the HTML with after? Because there's probably a way you can just do away with actually manipulating the HTML string beforehand. Here's a solution anyway:
string afterFirst = html.Substring(Regex.Match(html, emailFeedTxtStart).Index + emailFeedTxtStart.Length);
string between = afterFirst.Substring(0, Regex.Match(afterFirst, emailFeedTxtEnd).Index);

Writing a .CSV file usingt the LinqtoCSV DLL

I'm trying to write to a CSV file from a list using the LinqToCSV library found on http://www.codeproject.com/Articles/25133/LINQ-to-CSV-library#Installation.
When I try and run my program I keep getting a CsvColumnAtrributeRequiredException exception. So it's not filling a CSV file.
Here is my code:
private void button1_Click(object sender, EventArgs e) // merge files button
{
if(System.IO.File.Exists("OUTPUT.csv"))
{
System.IO.File.Delete("OUTPUT.csv");
output = new System.IO.StreamWriter("OUTPUT.csv");
}
else
{
output = new System.IO.StreamWriter("OUTPUT.csv");
}
String[] parts = new String[1000];
String[] parts2 = new String[1000];
parts = File.ReadAllLines(textBox1.Text); //gets filepath from top textbox
parts2 = File.ReadAllLines(textBox2.Text); //gets filepath from middle textbox
String[] head = File.ReadAllLines(headingFileBox.Text); //header file array
//merging the two files onto one list, there is no need to merge the header file because no math is being
//computed on it
var list = new List<String>();
list.AddRange(parts);
list.AddRange(parts2);
//foreach loop to write the header file into the output file
foreach (string h in head)
{
output.WriteLine(h);
}
//prints 3 blank lines for spaces
output.WriteLine();
output.WriteLine();
output.WriteLine("LEASE NAME" + "," + "FIELD NAME" + "," + "RESERVOIR" + "," + "OPERATOR" + "," +"COUNTY" + "," + "ST" + "," + "MAJO" + "," + "RESV CAT" + "," + "DISCOUNT RATE"
+ "," + "NET OIL INTEREST" + "," + "NET GAS INTEREST" + "," + " WORKING INTEREST" + "," + "GROSS WELLS" + "," + "ULT OIL" + "," + "ULT GAS" + "," + "GROSS OIL" + ","
+ "GROSS NGL" + "," + "GROSS GAS" + "," + "NET OIL" + "," + "NET GAS" + "," + "NET NGL" + "," +"REVENUE TO INT." + "," + "OPER. EXPENSE" + "," + "TOT INVEST." + ","
+ "REVENUE OIL" + "," + "REVNUE GAS" + "," + "OPERATING PROFIT" + "," + "REVENUE NGL" + "," + "DISC NET INCOME" + "," + "SEQ" + "," + "WELL ID" + "," + "INC ASN" + ","
+ "LIFE YEARS" + "," + "OWN QUAL" + "," + "PRODUCTION TAX" + "," + "AD VALOREM TAX");
output.WriteLine();
output.WriteLine();
String[] partsComb = list.ToArray(); // string array that takes in the list
Array.Sort(partsComb);
CsvFileDescription outputFileDescription = new CsvFileDescription
{
SeparatorChar = '\t',
FirstLineHasColumnNames = false,
};
CsvContext cc = new CsvContext();
cc.Write(partsComb ,output, outputFileDescription);
I'm just trying to get this up and running to output it correctly to a CSV file. Any help would be greatly appreciated.
Your code doesn't appear to be using any of the features of Linq2Csv.
You get the error because you're just trying to write a string out which doesn't have csvcolumn attribute.
Why do you think you need linq2csv? From your code you read in 2 files sort the lines from those files then try to write the result back out. You're not using any of Linq2csv's features. You could just write this result straight to a file & not use linq2csv.
Alternatively, create a class that matches the data you are reading, then follow the instructions in the article to read the file into a list of that class. merge & write back out again using linq2csv.
More Info
This line from the article reads the data in
IEnumerable<Product> products = cc.Read<Product>("products.csv", inputFileDescription);
You need to do this for each file you want to read into 2 lists eg parts & parts2 from your code.
having done this, follow the example for writing a file, but pass parts.union(parts2) instead of products2.
cc.Write(products2, "products2.csv", outputFileDescription);

GitHub API update file

I'm trying to update a file via the GitHub API.
I've got everything setup, and in the end the actual file is updated, which is a good thing.
However, let's say I've got these 2 files in my repo
FileToBeUpdated.txt
README.md
And then I run my program
The FileToBeUpdated.txt is updated, like it should, however the README.md is deleted.
This is the code with the 5 steps to update the file:
private static void Main()
{
string shaForLatestCommit = GetSHAForLatestCommit();
string shaBaseTree = GetShaBaseTree(shaForLatestCommit);
string shaNewTree = CreateTree(shaBaseTree);
string shaNewCommit = CreateCommit(shaForLatestCommit, shaNewTree);
SetHeadPointer(shaNewCommit);
}
private static void SetHeadPointer(string shaNewCommit)
{
WebClient webClient = GetMeAFreshWebClient();
string contents = "{" +
"\"sha\":" + "\"" + shaNewCommit + "\", " +
// "\"force\":" + "\"true\"" +
"}";
// TODO validate ?
string downloadString = webClient.UploadString(Constants.Start + Constants.PathToRepo + "refs/heads/master", "PATCH", contents);
}
private static string CreateCommit(string latestCommit, string shaNewTree)
{
WebClient webClient = GetMeAFreshWebClient();
string contents = "{" +
"\"parents\" :[ \"" + latestCommit + "\" ], " +
"\"tree\":" + "\"" + shaNewTree + "\", " +
"\"message\":" + "\"test\", " +
"\"author\": { \"name\": \""+ Constants.Username +"\", \"email\": \""+ Constants.Email+"\",\"date\": \"" + DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture) + "\"}" +
"}";
string downloadString = webClient.UploadString(Constants.Start + Constants.PathToRepo + "commits", contents);
var foo = JsonConvert.DeserializeObject<CommitRootObject>(downloadString);
return foo.sha;
}
private static string CreateTree(string shaBaseTree)
{
WebClient webClient = GetMeAFreshWebClient();
string contents = "{" +
"\"tree\" :" +
"[ {" +
"\"base_tree\": " + "\"" + shaBaseTree + "\"" + "," +
"\"path\": " + "\"" + Constants.FileToChange + "\"" + " ," +
"\"content\":" + "\"" + DateTime.Now.ToLongTimeString() + "\"" +
"} ]" +
"}";
string downloadString = webClient.UploadString(Constants.Start + Constants.PathToRepo + "trees", contents);
var foo = JsonConvert.DeserializeObject<TreeRootObject>(downloadString);
return foo.sha;
}
private static string GetShaBaseTree(string latestCommit)
{
WebClient webClient = GetMeAFreshWebClient();
string downloadString = webClient.DownloadString(Constants.Start + Constants.PathToRepo + "commits/" + latestCommit);
var foo = JsonConvert.DeserializeObject<CommitRootObject>(downloadString);
return foo.tree.sha;
}
private static string GetSHAForLatestCommit()
{
WebClient webClient = GetMeAFreshWebClient();
string downloadString = webClient.DownloadString(Constants.Start + Constants.PathToRepo + "refs/heads/master");
var foo = JsonConvert.DeserializeObject<HeadRootObject>(downloadString);
return foo.#object.sha;
}
private static WebClient GetMeAFreshWebClient()
{
var webClient = new WebClient();
webClient.Headers.Add(string.Format("Authorization: token {0}", Constants.OAuthToken));
return webClient;
}
Which part am I missing? Am I using the wrong tree to start from?
It seems that in the function CreateTree I should set the base_tree at the root level, not at the level of each tree I create.
So in the function CreateTree the contents become this:
string contents = "{" +
"\"base_tree\": " + "\"" + shaBaseTree + "\"" + "," + // IT'S THIS LINE!
"\"tree\" :" +
"[ {" +
"\"path\": " + "\"" + Constants.FileToChange + "\"" + " ," +
"\"content\":" + "\"" + DateTime.Now.ToLongTimeString() + "\"" +
"} ]" +
"}";
Updated GitHub documentation: https://github.com/Snakiej/developer.github.com/commit/2c4f93003703f68c4c8a436df8cf18e615e293c7

Categories