Syed Muhammad Mubashir
Syed Muhammad Mubashir

Reputation: 1016

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;

Upvotes: 0

Views: 1007

Answers (2)

James Thorpe
James Thorpe

Reputation: 32202

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");

Upvotes: 0

EagleBeak
EagleBeak

Reputation: 7419

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" }

Upvotes: 1

Related Questions