How do I convert json string to key\value pairs? - c#

I want to take all the key-value pairs after the \"tags\" under "instanceData" and make them key-value pairs under "properties".
I have this...
{
"id": "/subscriptions/1234abcd-ab12-12ab-12ab-abcdfghi1234/Daily_BRSDT_20161214_0000",
"name": "Daily_BRSDT_20161214_0000",
"type": "Microsoft.Commerce/UsageAggregate",
"properties": {
"subscriptionId": "1234abcd-ab12-12ab-12ab-abcdfghi1234",
"usageStartTime": "2017-03-08T00:00:00+00:00",
"usageEndTime": "2017-03-09T00:00:00+00:00",
"meterName": "Standard IO - File Read Operation Units (in 10,000s)",
"meterCategory": "Data Management",
"unit": "10,000s",
"instanceData": "{\"Microsoft.Resources\":{\"resourceUri\":\"/subscriptions/1234abcd-ab12-12ab-12ab-abcdfghi1234/resourceGroups/default-resource-group67/providers/Microsoft.Storage/storageAccounts/defaultstorage67\",\"location\":\"ussouthcentral\",\"tags\":{\"ProjectName\":\"default Portal\",\"billTo\":\"Technology\",\"component\":\"Persistant Storage\",\"department\":\"Technology\",\"displayName\":\"default Portal Storage Account\",\"enviornment\":\"default\",\"function\":\"Reporting\",\"matterNumber\":\"999999\",\"primaryowner\":\"john#internet.com\",\"productLine\":\"Information Components\",\"secondaryowner\":\"mary#internet.com\",\"version\":\"1.0.0.0\"}}}",
"meterId": "12345ab-259d-4206-a6ae-12345678abcd",
"infoFields": {},
"quantity": 0.0004
}
}
I want this...
{
"id": "/subscriptions/1234abcd-ab12-12ab-12ab-abcdfghi1234/Daily_BRSDT_20161214_0000",
"name": "Daily_BRSDT_20161214_0000",
"type": "Microsoft.Commerce/UsageAggregate",
"properties": {
"subscriptionId": "1234abcd-ab12-12ab-12ab-abcdfghi1234",
"usageStartTime": "2017-03-08T00:00:00+00:00",
"usageEndTime": "2017-03-09T00:00:00+00:00",
"meterName": "Standard IO - File Read Operation Units (in 10,000s)",
"meterCategory": "Data Management",
"unit": "10,000s",
"instanceData": "{\"Microsoft.Resources\":{\"resourceUri\":\"/subscriptions/1234abcd-ab12-12ab-12ab-abcdfghi1234/resourceGroups/default-resource-group67/providers/Microsoft.Storage/storageAccounts/defaultstorage67\",\"location\":\"ussouthcentral\"}}",
"ProjectName":"default Portal",
"billTo":"Technology",
"component":"Persistant Storage",
"department":"Technology",
"displayName":"default Portal Storage Account",
"enviornment":"default",
"function":"Reporting",
"matterNumber":"999999",
"primaryowner":"john#internet.com",
"productLine":"Information Components",
"secondaryowner":"mary#internet.com",
"version":"1.0.0.0",
"meterId": "12345ab-259d-4206-a6ae-12345678abcd",
"infoFields": {},
"quantity": 0.0004
}
}
Is there a simple way to convert this? I am attempting to do this with RegEx with no luck.

I would recommend looking at something like this:
How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?
Serialize List<KeyValuePair<string, string>> as JSON
Effectively you're going to need to strip out the one key you want to be parsed, and re-add that to your JSON object.
Json.NET - Newtonsoft's tool is great for working with JSON.
http://www.newtonsoft.com/json
Easiest way to do it:
Convert your entire JSON string to a Dictionary or to a List<KeyValuePair<string,string>>.
Take the instanceData bit you want to split apart, and then parse it into another C# object.
Merge both objects together using some logic to ensure no duplicate keys.
Serialize your object back into JSON
This is an easy way to do it, though not the most efficient way.

Related

Can't parse json into JArray object after using JSON_ARRAY and JSON_OBJECT in mysql

I'm querying a mySQL (MariaDB) database and use JSON_ARRAY and JSON_OBJECT to gather json objects as array.
I have an api to retrieve the data from the DB, by using GetAsync.
Afterwards, in the api consumer, I want to parse the Json into an object,
using JArray (Newtonsoft).
I can't manage to parse the Json due to problem in the JSON_OBJECT (it seems like a quote wrapping the array sign "["). See error code below.
What am I doing wrong and how can I fix it ?
When getting another Json from another data source (not using JSON_ARRAY and JSON_OBJECT), parsing is working (see example below)
This is my code:
public JARrray parse(HttpResponseMessage response)
{
return JArray.Parse(response.Content.ReadAsStringAsync().Result);
}
This is the string that works:
[
{
"remark":"",
"driver": [
{
"username":"0000000",
"uid":"00000000",
"fname": "000000",
"lname": ""
}
]
}
]
And this is the string that get the message
After parsing a value an unexpected character was encountered: u. Path '[0].driver', line..."
I can see in the stack that this is happening on the line:
JsonTextReader.ParsePostValue(Boolean ignoreComments):
Json:
[
{
"remark":"",
"driver": "[{\"username\": \"0000000\", \"uid\": \"00000000\", \"fname\":\"ZZZZZ\", \"lname\":\"\"}]"
}
]
or even, when I removing the "" :
[
{
"remark":"",
"driver": "[{"username": "0000000", "uid": "00000000", "fname":"ZZZZZ", "lname":""}]"
}
]
\"fname\":"\ZZZZZ\"
The escaped double quote in front of ZZZZZ is wrong. Change it from "\ to \".

How do you dynamically parse, read, and append to JSON with multiple sub arrays

After a bunch of research I haven't been able to find any good ways to read a json file, store their values, then append a new object/array to it.
The JSON looks like
{
"Skywars": [
{
"Solo Normal": [
{
"000001": [
{
"Kills": 213,
"Deaths": 117
}
]
}
],
"Solo Insane": [
{
"000001": [
{
"Kills": 10790,
"Deaths": 7184
}
]
}
]
}
],"Bedwars": [
{
"Solo": [
{
"000001": [
{
"Kills": 0,
"Deaths": 0
}
]
}
],
"Duos": [
{
"000001": [
{
"Kills": 0,
"Deaths": 0
}
]
}
]
}
]
}
As an example, i am intending for it to go "Skywars.Solo Normal", "Skywars.Solo Insane", "Bedwars.Solo", "Bedwars.Duos" then append "000002" with new kills and deaths values.
For some reason, even after hours of searching, I can't find out how to read the kills and deaths (I've gotten close, using public Skywars[] Skywars { get;set; }. Problem is most of the examples are using JSON files that look like {"user":[{"id":1,"logins":0}]} with very little arrays & sub arrays.
To anyone who is kind enough to answer, please don't spoonfeed me code, explain how it would be done (would I need to create my own parser, etc), or if there are already any posts/links that answer my question (even though I failed to find how).
Notes -
"000001" and "000002" will be dynamic, so each time you start the program those values will be different. I just want to append after the last instance of stats saved.
Also sorry, I am still learning C# but know most of the basics and some more complex concepts, I've just never been good at storing data and using JSON. If you need anything to help else just add a comment and I'll add it.
Please see Json.NET's Modifying JSON.
This sample loads JSON, modifies JObject and JArray instances and then writes the JSON back out again.
Sample
string json = #"{
'channel': {
'title': 'Star Wars',
'link': 'http://www.starwars.com',
'description': 'Star Wars blog.',
'obsolete': 'Obsolete value',
'item': []
}
}";
JObject rss = JObject.Parse(json);
JObject channel = (JObject)rss["channel"];
channel["title"] = ((string)channel["title"]).ToUpper();
channel["description"] = ((string)channel["description"]).ToUpper();
channel.Property("obsolete").Remove();
channel.Property("description").AddAfterSelf(new JProperty("new", "New value"));
JArray item = (JArray)channel["item"];
item.Add("Item 1");
item.Add("Item 2");
Console.WriteLine(rss.ToString());
// {
// "channel": {
// "title": "STAR WARS",
// "link": "http://www.starwars.com",
// "description": "STAR WARS BLOG.",
// "new": "New value",
// "item": [
// "Item 1",
// "Item 2"
// ]
// }
// }

Newtonsoft.Json - Unexpected characters while parsing value

I'm pulling intents back from API.AI and parsing these to C# objects using Newtonsoft.Json in the following way:-
intentListModel = JsonConvert.DeserializeObject<List<IntentListModel>>(intentList);
intentList is a JSON string from the webrequest. However at Line 1, position 161, it fails. The bit of JSON concerned is:-
"contextIn": [
"Employed"
],
"events": [{
"name": "Occupation_DOB"
}],
NB: This is only part of the JSON, and the JSON opens and closes with [] as it is a list of JSON items.
specifically the opening { on events. I'm stumped, I've run it through a validator and I see valid JSON.
Could anyone suggest what I can try, or is there a setting somewhere for this? Or is the error message actually looking another area of the JSON string?
Thanks in advance!
UPDATE
Whole JSON sample posted
[
{
"id":"18b025c5-3567-49c1-a9e9-25583f9156ca",
"name":"IncomeProtection - Employed? - Occupation/DOB/Email",
"state":"LOADED",
"contextIn":[
"Employed"
],
"events":[
{
"name":"Occupation_DOB"
}
],
"parentId":"ad5f0007-c084-4615-93dd-6c82ca5e7602",
"parameters":[
{
"required":true,
"dataType":"#Occupation",
"name":"Occupation",
"value":"$Occupation",
"prompts":[
"Whatu0027s your Occupation?"
],
"isList":false
},
{
"required":true,
"dataType":"#sys.date",
"name":"date",
"value":"$date",
"prompts":[
"Whatu0027s your date of birth?"
],
"isList":false
}
],
"contextOut":[
{
"name":"OccupationDOB",
"parameters":{
},
"lifespan":1
}
],
"actions":[
"IncomeProtection:Occupation/DOB"
],
"priority":500000,
"fallbackIntent":false
}
]
This issue was down to one of the items from the API being returned in a list, but in the particular example I looked at, the API returned a list of 1 item. I misread the brackets and created a class property of type string instead of List<string>, hence the failure of code.
Hope this helps people in the future.

Want to check if youtube url(video) is exist and date published/modified using vb.net

I have requirement where I have excel sheet contains youtube URLs. I want to fetch this URLs and validate with youtube. I want below information.
- Whether URL/video is exist.
- Date created/updated.
- Whether URL/video was exist but deleted now. If so, deleted date.
I want to achieve this in windows application using vb.net without using youtube API.
Also, I want to read/update excel in vb.net without using OleDBDataProvider and Microsoft.Office.Interop.
Can somebody please help me out on this.
Thanks
First, to check the if the video is existing, you can use the Videos: list to return a videos that match the API request. By doing this, you can now verify if the videoId of the video is existing or not.
Here is the sample request, just pass id as your part parameter and the videoId in the id parameter.
{
"kind": "youtube#videoListResponse",
"etag": "\"uQc-MPTsstrHkQcRXL3IWLmeNsM/ZHvOwtluy6sCNoIMjJVPsNKhBTc\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "\"uQc-MPTsstrHkQcRXL3IWLmeNsM/m-PtiixITeo8icgmD0t6X8DGyMA\"",
"id": "kmXXXLBL3Nk"
}
]
}
Now, if the videoId is invalid or not existing your response should look like this:
{
"kind": "youtube#videoListResponse",
"etag": "\"uQc-MPTsstrHkQcRXL3IWLmeNsM/ZCAnB4VKeQ7X3vzSCnmpxyOQqUk\"",
"pageInfo": {
"totalResults": 0,
"resultsPerPage": 0
},
"items": [
]
}
For the date published, you can use the part snippet like this to get the date in the publishedAt
"kind": "youtube#video",
"etag": "\"uQc-MPTsstrHkQcRXL3IWLmeNsM/uVmd9wiVAjnCz_wJuE9qrbXsJRU\"",
"id": "kmXXXLBL3Nk",
"snippet": {
"publishedAt": "2016-10-20T08:08:19.000Z",
"channelId": "UCTEAryTk0JGFSLNZ0tBIw2w",
"title": "Kobe's Last 3 minutes and 20 seconds Lakers Jazz 4 13 2016",
"description": "#IDOL",

Get JSON object node

I have a json object and I want to get the value of :
entities > media > sizes > large > h
Is there a way to get it like XML -> Xpath method?
This is extra lines that is irrelevant to question just because of ...
{
"created_at": "Sun, 01 Jan 2012 17:05:32 +0000",
"entities": {
"user_mentions": [
{
"screen_name": "nurdanterbiyik",
"name": "nurdan",
"id": 264782080,
"id_str": "264782080",
"indices": [
0,
15
]
}
],
"media": [
{
"id": 153522253777219584,
"id_str": "153522253777219584",
"indices": [
44,
64
],
"media_url": "http://p.twimg.com/AiFrrSmCMAAdEID.jpg",
"media_url_https": "https://p.twimg.com/AiFrrSmCMAAdEID.jpg",
"url": "http://t.co/ZwHN9gvO",
"display_url": "pic.twitter.com/ZwHN9gvO",
"expanded_url": "http://twitter.com/emelkiraac/status/153522253773025280/photo/1",
"type": "photo",
"sizes": {
"large": {
"w": 536,
"h": 800,
"resize": "fit"
},
Using JSON.NET you have several ways to read data without having to deserialize your JSON text into objects. Here is a simplified example:
string json = #" {
""created_at"": ""Sun, 01 Jan 2012 17:05:32 +0000"",
""entities"": {
""media"": [{
""type"": ""photo"",
""sizes"": {
""large"": {
""w"": 536,
""h"": 800,
""resize"": ""fit""
}
}
}]
}
}
";
JObject o = JObject.Parse(json);
int h = (int)o["entities"]["media"][0]["sizes"]["large"]["h"];
int h2 = (int)o.SelectToken("entities.media[0].sizes.large.h");
I prefer to think of JSON purely as serialized objects--the first and last thing I want to do with it is to de-serialize it into the objects that I then work with.
I can't tell you the best way to do it in c#, but I've had good luck using JSON.NET
JSON.NET will also let you (quote from website) "LINQ to JSON is good for situations where you are only interested in getting values from JSON, you don't have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects. LINQ to JSON allows you to easily read, create and modify JSON in .NET.", which sounds like what you are trying to do. I've never tried it, but if all you're trying to do is get one piece of data out of that long string, then it sounds like a good alternative.

Categories

Resources