Search code examples
c#json.netjsonpath

Using a variable in JToken query


From the docs https://www.newtonsoft.com/json/help/html/SelectToken.htm

IEnumerable<JToken> price = o.SelectTokens("$..Products[?(@.Name == "AAA")].Price");

How could I re-write the above query where I have to find prices to match multiple product names from a list ["AAA", "BBB", "CCC"]


Solution

  • Consider using SelectToken with LINQ in the same link you provided.

    To achieve your goal, you can write something like:

    var names = new string[]{"AAA", "BBB", "CCC"};
    var prices = o.SelectTokens("$..Products[*]")
           .Where(p => names.Contains((string)p["Name"]))
           .Select(p => (decimal)p["Price"])
           .ToList();