-1

Here is my JSON which I have parsed to a JObject. Can I get the string array for ExternalRateId from the below using SelectToken?

As of now, I'm using foreach() to loop through and get the list of them and converting it to a string. Can we solve this in much easier way using SelectToken(). If so please show me the best way to do this.

{
    "RateCards": [
        {
            "ExternalRateCardId": "62283ab4",
            "Rates": [
                {
                    "ExternalRateId": "2a77db10",
                }
            ],
            "IsUpdate": false
        },
        {
            "ExternalRateCardId": "f6878b23",
            "Rates": [
                {
                    "ExternalRateId": "2a739550",
                }
            ],
            "IsUpdate": false
        },
        {
            "ExternalRateCardId": "3f51162c",
            "Rates": [
                {
                    "ExternalRateId": "2a751bf0",
                }
            ],
            "IsUpdate": false
        }
    ]
}
Metro Smurf
  • 37,266
  • 20
  • 108
  • 140
  • I'm guessing the 'jquery' tag is an error here given your mention of JObject and SelectToken...? – Rory McCrossan Sep 09 '22 at 15:28
  • Also, what do you mean by *get the string array for `ExternalRateId`*? There is an outer array `RateCards` and an inner array `ExternalRateId`, what exactly do you want? a `string [][]` jagged array? a `string []` array with the inner array flattened? Something else? If you could [edit] your question to share your current code that would help to clarify. See [ask]. – dbc Sep 09 '22 at 15:46
  • Assuming c#, then rather than manually parsing to `JObject` you could just auto-generate a data model using one of the tools from [here](https://stackoverflow.com/q/21611674/3744182). See https://dotnetfiddle.net/8CBqYc. Or if you are not allowed to define a data model for some reason, you can use a JSONPath wildcard e.g. like so: `jObject.SelectTokens("RateCards[*].Rates[*].ExternalRateId").Select(r => (string)r).ToArray();`, see https://dotnetfiddle.net/wehpOx. But it's not clear what your requirements are, so please [edit] your question to clarify. – dbc Sep 09 '22 at 16:34

1 Answers1

1

you can use LINQ

List<string> externalRateIds = ((JArray)JObject.Parse(json)["RateCards"])
        .SelectMany(x => x["Rates"].Select(x => (string)x["ExternalRateId"]))
        .ToList();

or if you want a weird syntax with SelectToken

string[] externalRateIds = ((JArray)JObject.Parse(json).SelectToken("RateCards"))
 .SelectMany(x => x.SelectToken("Rates")
 .Select(x => x.SelectToken("ExternalRateId").Value<string>())
.ToArray();
Serge
  • 40,935
  • 4
  • 18
  • 45