简体   繁体   中英

How To Replace SubString Of JSon String With Required Substring

Following string contains JSon parsed string.

      string myJSonString="{ \"_id\" : { \"$oid\" : \"54f6b062036de221c00f5540\" }, \"account\" : \"Acc1\", \"accuser\" : \"\", \"curstatus\" : \"booked\" }";

      string oldString=" { \"$oid\" :";
      string newString="";

I am using below code for replacing the substring using regex but it doesn't work;

    string   result = Regex.Replace(myJSonString, oldString, newString, RegexOptions.IgnoreCase);

Second Replace

    string oldStrin="}, \"account\"";
   string newString=", \"account\"";
  string   finalResult = Regex.Replace(result , oldString2, newString2, RegexOptions.IgnoreCase);

This code doesn't work for me;

If it's really as simple as in your example, I would use a regular string replacement, which I find much easier to understand:

string myJSonString="{ \"_id\" : { \"$oid\" : \"54f6b062036de221c00f5540\" }, \"account\" : \"Acc1\", \"accuser\" : \"\", \"curstatus\" : \"booked\" }";

string result = myJSonString.Replace(" { \"$oid\" :", "").Replace("}, \"account\"", ", \"account\"");

//{ "_id" : "54f6b062036de221c00f5540" , "account" : "Acc1", "accuser" : "", "curstatus" : "booked" }

Your version probably isn't working due to the fact that $ is a special character in regular expressions - it is an anchor , denoting the end of a line or the end of a string, so it needs to be escaped with a \\ .

Having said that, rather than replacing the section before and after the ID with nothing, instead we can construct a single regex to find the entire section and replace it with just the inner ID:

string pattern = "{ \"\\$oid\" : (\"[a-z0-9]+\") }";

string myJSonString = "{ \"_id\" : { \"$oid\" : \"54f6b062036de221c00f5540\" }, \"account\" : \"Acc1\", \"accuser\" : \"\", \"curstatus\" : \"booked\" }";

string finalResult = Regex.Replace(myJSonString, pattern, "$1");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM