joshua
joshua

Reputation: 2371

Find JToken if value matches with a given pattern

I am trying to find JToken in JArray where any JToken Value matched with __ .

the JArray is something like this , its easier if Key is known i.e. if give text as key I can find all JToken , but if I try to solve by value where key is unknown . Not able to fit that piece of code

"annotations": [
    {
      "align": "right",
      "axref": "x",
      "ayref": "y2",
      "font": {
        "size": 12,
        "family": "Arial,Helvetica,sans-serif"
      },
      "showarrow": false,
      "text": "D16-__m__0",
      "x": 1,
      "xanchor": "right",
      "xref": "paper",
      "y": 16,
      "yanchor": "top",
      "yref": "y2"
    },
    {
      "showarrow": false,
      "font": {
        "size": 12,
        "family": "Arial,Helvetica,sans-serif"
      },
      "text": "Something",
      "textangle": -90,
      "x": "__gh__",
      "xanchor": "right",
      "y": 0.5,
      "yanchor": "middle",
      "yref": "paper"
    }
  ]

I tried something like this but Value kind i am not sure how do .

destination["annotations"] .Children<JObject>().Where(x => x?["text"] != null && x["text"].Value<string>().Contains($"__{somevalue}__"))
                                                             

but this gives error

destination["annotations"].Children().Where(x => x.Value<string>().Contains($"__{somevalue}__")))

Upvotes: 1

Views: 286

Answers (1)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23228

You can use Descendants() method here, get all properties and filter them by checking __ string in value

var json = JObject.Parse(jsonString);

var result = json.Descendants().OfType<JProperty>().Where(p =>
    p.Value.Type == JTokenType.String && p.Value.Value<string>().Contains("__"));

Upvotes: 2

Related Questions