user11967010
user11967010

Reputation:

C# check if JSON File contains string

I am trying to make it so I can check whether a string is in a json.

For exmaple, in my JSON file exists name = Disp_R, name = Disp_L, name = Disp_C. And whenever Disp is in the string, the whole value should be stored in a list

Thats how I do it, but it don't work with the regex

 var jTempObj = JObject.Parse(starcInformation.DeviceArray);
 var tempItems = jTempObj.SelectTokens("$..items[?(@.name=='" + xmlInformation.Device + "')]");
            
 foreach (var item in tempItems)
 {
     DeviceList.Add(item["name"].ToString());
 }

I hope someone can help me :) Thanks a lot

edit

Part1 Part2

Upvotes: 2

Views: 1773

Answers (2)

Guru Stron
Guru Stron

Reputation: 141575

Json path supports matching javascript regexes, so something like this should work:

var js = "{items:[{'name':'DISP_1'}, {'name':'DISP_2'}, {'name':'sa'}, {'name':'DISP_'}]}";
var result = JObject.Parse(js).SelectTokens("$.items[?(@.name =~ /DISP_.+/)]");

Result will contain all tokens prefixed with DISP_ and having at least one symbol after it.

Upvotes: 0

murtaza sanjeliwala
murtaza sanjeliwala

Reputation: 205

You can stringify json using

JsonConvert.SerializeObject(json)

than you can find specific string inside it using

if(str.Contains("--your-string---"))

Upvotes: 1

Related Questions