Home > Back-end >  How to extract specific value from this json string using linq
How to extract specific value from this json string using linq

Time:04-28

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.

CodePudding user response:

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);

CodePudding user response:

Anand Sowmithiran had the answer:

JObject observationsJobject = JObject.Parse(observationsJson);
        string csvDownloadHref = (string)observationsJobject.SelectToken("downloads.csv.href");
        return csvDownloadHref;
  • Related