access value in JSONArray C# UWP - c#

I want to extract the first value in a JSONArray as String. Somehow I have the wrong approach, I get an exception.
How can I improve this?
I think I reach the array fine via myJasonObject["entities"].toArray(), but when I try to do something like getString()["entity"] afterwards, it's marked as error by VS.
I want to be able to store "dax" (the value of "entity"):
Response{
"query": "what about dax",
"topScoringIntent": {
"intent": "StockPrice2",
"score": 0.3969668
},
"intents": [
{
"intent": "StockPrice2",
"score": 0.3969668
},
{
"intent": "None",
"score": 0.372112036
},
],
"entities": [
{
"entity": "dax",
"type": "StockSymbol"
}
]
}

You can get "dax" using following:
JObject obj = JObject.Parse(json);
JArray entities = obj.GetValue("entities") as JArray;
var firstEntity = entities.FirstOrDefault() as JObject;
var entityPropertyValue = entity.GetValue("entity");
var daxString = entityPropertyValue.ToString();

Related

How to extract specific value from this json string using linq

could anyone help me extract the specific value for [downloads][csv][href] out of the following json string please?
{
"#context": "https://cdn.ons.gov.uk/assets/json-ld/context.json",
"alerts": [],
"collection_id": "cmdr",
"dimensions": [
various dimensions here
],
"downloads": {
"csv": {
"href": "https://download.beta.ons.gov.uk/downloads/datasets/regional-gdp-by-year/editions/time-series/versions/4.csv",
"size": "568021"
},
"csvw": {
"href": "ref",
"size": "1903"
},
"xls": {
"href": "ref",
"size": "80768"
}
},
"edition": "time-series",
"id": "5c",
"links": {
"dataset": {
"href": "ref",
"id": "regional-gdp-by-year"
},
"edition": {
"href": "ref",
"id": "time-series"
},
"self": {
"href": "ref"
}
},
"release_date": "2021",
"state": "published",
"usage_notes": [],
"version": 4
}
the current code I am using returns nothing:
var labels = JObject.Parse(observationsJson)["downloads"];
var results = labels.Select(data => new
{
label = (string)data["href"]
});
foreach (var item in results)
{
csvDownloadAddress = item.label;
}
If there is another method rather than using linq then I am open to suggestions.
Sorry if this is a dumb quest, my experience with linq and json is very limited.
thank you for your help.
You have JSON Path, that can be used to select specific element(s) from the JSON string.
see Newtonsoft example, or you can use this JsonPath Nuget package.
The JsonPath Nuget can be used like below,
var input = "$.downloads.csv.href";
var path = JsonPath.Parse(input);
var hrefVal = path.Evaluate(jsonStr);

Transform a JSON object to a JSON array, taking the first level of properties

I've this JSON object
{
"08f4f705-6e14-4781-8241-d04bf2dc6ada": {
"description": "xxxxxxxx",
"note": "yyyyyyyy"
},
"05f4f995-6e14-4567-8241-d04bf2d456ee": {
"description": "aaaaaa",
"note": "bbb"
},
"0675f995-6e14-4567-8241-d4567f2d456z": {
"description": "fffff",
"note": "gggg"
}
}
I need to convert into a JSON array like this:
(the elements should be the content of the first level properties)
[
{
"description": "xxxxxxxx",
"note": "yyyyyyyy"
},
{
"description": "aaaaaa",
"note": "bbb"
},
{
"description": "fffff",
"note": "gggg"
}
]
I can't manipulate the object and I didn't find an appropriate resource to follow. How can I do it?
You can achieve this by deserializing your json string into Dictionary<string, object>:
var obj = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
After that you extract the values and serialize them back to json:
var newJson = JsonConvert.SerializeObject(obj.Values);

Accesing child value in JSON

How can i acces the first item id?
using (var http = new HttpClient())
{
var res = JArray.Parse(await http.GetStringAsync("http://api.champion.gg/champion/Gragas?api_key=????").ConfigureAwait(false));
^^^^^^ // Also tried with JObject instead of JArray, both don't work
var champion = (Uri.EscapeUriString(res[0]["items"][0]["mostGames"][0]["items"][0]["id"].ToString()));
Console.WriteLine(champion); // ^ [0] here because the JSON starts with an [
}
Example JSON result (made it smaller because the original JSON is over 21500 characters, made sure its valid with https://jsonlint.com, here is the original JSON response: https://hastebin.com/sacikozano.json)
[{
"key": "Gragas",
"role": "Jungle",
"overallPosition": {
"change": 1,
"position": 13
},
"items": {
"mostGames": {
"items": [{
"id": 1402,
"name": "Enchantment: Runic Echoes"
},
{
"id": 3158,
"name": "Ionian Boots of Lucidity"
},
{
"id": 3025,
"name": "Iceborn Gauntlet"
},
{
"id": 3065,
"name": "Spirit Visage"
},
{
"id": 3742,
"name": "Dead Man's Plate"
},
{
"id": 3026,
"name": "Guardian Angel"
}
],
"winPercent": 50.45,
"games": 300
}
}
}]
With JArray i get the following error: Accessed JObject values with invalid key value: 0. Object property name expected.
With JObject i get the following error: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
Thanks in advance, i hope i explained it well
It should be:
var champion = (Uri.EscapeUriString(res[0]["items"]["mostGames"]["items"][0]["id"].ToString()));
The outermost "items" property has a single object as its value, not an array, so [0] is not needed in ["items"][0]. Similarly "mostGames" has a single object value so the [0] is not needed in ["mostGames"][0].
Sample fiddle.
Note that if "items" is sometimes an array of objects, but sometimes is a single object instead of an array of one object, you can introduce the following extension method:
public static class JsonExtensions
{
public static IEnumerable<JToken> AsArray(this JToken item)
{
if (item is JArray)
return (JArray)item;
return new[] { item };
}
}
And do:
var champion = (Uri.EscapeUriString(res[0]["items"].AsArray().First()["mostGames"]["items"][0]["id"].ToString()));

How to extract ID from the following JSON Object in C#?

I want to extract all IDs from the below object using c#.
in need of extracting a response value in a visual studio webtest.
The JSON is obtained using extract event.
{
"d": [
{
"__type": "QuestionZoneEditor.Entities.QuestionTag",
"Id": 2080,
"Name": "01",
"Items": [
"1a",
"1b",
"1c",
"1d"
]
},
{
"__type": "QuestionZoneEditor.Entities.QuestionTag",
"Id": 2081,
"Name": "02",
"Items": [
"2a(i)",
"2a(ii)",
"2b",
"2c"
]
},
{
"__type": "QuestionZoneEditor.Entities.QuestionTag",
"Id": 2082,
"Name": "03",
"Items": [
"3a",
"3b",
"3c"
]
}
}
]
}
Deserialize it to JObject after that take all JObject from the JArray and print the Id
var result = JsonConvert.DeserializeObject<JObject>(json);
foreach(JObject obj in result["d"])
{
Console.WriteLine(obj["Id"]);
}
Full example: dotNetFiddle

Deserialize Dynamic Json string using Newtonsoft JSON.NET

I have a JSON string that I'm getting from Facebook API, in which I have a node whose name changes according to its content, for example some time it is 45, or 58 etc.
It could be any number.
I want its value. How to get it?
Example:
{
"data": [
{
"id": "1492292372_10201810786059989",
"created_time": "2014-04-05T09:00:54+0000"
},
{
"id": "1492292372_10201804679827337",
"created_time": "2014-04-04T07:29:07+0000"
},
{
"id": "1492292372_10201804649306574",
"created_time": "2014-04-04T07:10:33+0000"
},
{
"id": "1492292372_10201801316823264",
"created_time": "2014-04-03T18:31:50+0000"
},
{
"id": "1492292372_10201798962284402",
"created_time": "2014-04-03T06:24:47+0000"
},
{
"message_tags": {
"0": [
{
"id": "1492292372",
"name": "Yawar Sohail",
"type": "user",
"offset": 0,
"length": 12
}
],
"15": [
{
"id": "1489845168",
"name": "Zeeshan Anjum",
"type": "user",
"offset": 15,
"length": 13
}
]
},
"id": "1492292372_10201796274777216",
"created_time": "2014-04-02T17:57:05+0000"
},
{
"id": "1492292372_10201794080482360",
"created_time": "2014-04-02T07:26:23+0000"
},
Inside message_tags there are two nodes [0 and 15] they dynamically changes according to their offset values. I want names, type and ids inside these nodes.
You can deserialize your JSON into an ExpandoObject:
var converter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, converter);
Which dynamically adds members to your object at runtime, and allows you to iterate over them as described in this answer:
foreach (var prop in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
Console.WriteLine("Name: {0}, Value: {1}",prop.Name, prop.GetValue(obj,null));
}
That way you can iterate over obj.message_tags to get the individual messages, and obtain all their details respectively.

Categories

Resources