Replace field in Json file with some other value.

Question

Tuesday, July 11, 2017 12:29 PM

Hi ,

I need to replace "f" with frequency in below json code. How can i achieve it using C# code?

{"request":{"command":"series","series_id":"PET.WTTEXUS2.W"},"series":[{"series_id":"PET.WTTEXUS2.W","name":"U.S. Exports of Crude Oil and Petroleum Products, Weekly","units":"Thousand Barrels per Day","f":"W","unitsshort":"Mbbl\/d","description":"U.S. Exports of Crude Oil and Petroleum Products","copyright":"None","source":"EIA, U.S. Energy Information Administration","iso3166":"USA","geography":"USA","geography2":"USA","start":"19910208","end":"20170630","updated":"2017-07-06T13:19:17-0400","data":[["20170630",5116],["20170623",5599],["20170616",4897],["20170609",5170]]}]}

Thanks

Syed

All replies (7)

Tuesday, July 11, 2017 9:02 PM

Hello SyedF,

There are many ways to achieve this.  The simplest is to to find the location of the f based on some nearby unique value.  Potentially this could be something like the following:

var numberOfBarrels = "111";
var myString = "";
var start = myString.IndexOf("Thousand Barrels per Day");
var fLocation = myString.IndexOf("\"f\"", start);
var newString = myString.Substring(0, fLocation) + numberOfBarrels + myString.Substring(fLocation + 2);

Another way would be to use a library like Json.Net.  The following should start you in the right direction:

http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm

Cheers, Jeff


Wednesday, July 12, 2017 5:01 AM

Hey SyedF,

Could you please tell us the data structure holding your json info?

Is it in a plain text file? Is it in a string? Is it a JObject?

And where do you expected the output? In place replacement in the file? String on the screen?

Thanks!

I build UWPs: Arrnage Pro, Cloud Resource Tools


Wednesday, July 12, 2017 5:15 AM | 1 vote

Hi Syed,

I saved your string to a .json file (easier to deal with all the quotes by just reading it in from a file), read in the file and then simply replaced "f": with "frequency":

string test = File.ReadAllText("TestJsonReplace.json");
string replace = test.Replace("\"f\":", "\"frequency\":");

If you need to write that back out to the file, you could do that easily enough with File.WriteAllText(). You didn't say how you got the Json string or what you needed to do with the new string, but the above will at least do the replacements you wanted.

~~Bonnie DeWitt [C# MVP]

http://geek-goddess-bonnie.blogspot.com


Wednesday, July 12, 2017 5:39 AM

Try this longer solution too:

string example = @"{""request"":{""command"":""series"",""series_id"":""PET.WTTEXUS2.W""},""series"":[{""series_id"":""PET.WTTEXUS2.W"",""name"":""U.S.Exports of Crude Oil and Petroleum Products, Weekly"",""units"":""Thousand Barrels per Day"",""f"":""W"",""unitsshort"":""Mbbl\/ d"",""description"":""U.S.Exports of Crude Oil and Petroleum Products"",""copyright"":""None"",""source"":""EIA, U.S.Energy Information Administration"",""iso3166"":""USA"",""geography"":""USA"",""geography2"":""USA"",""start"":""19910208"",""end"":""20170630"",""updated"":""2017 - 07 - 06T13: 19:17 - 0400"",""data"":[[""20170630"",5116],[""20170623"",5599],[""20170616"",4897],[""20170609"",5170]]}]}";

var s = new JavaScriptSerializer();
var o = (System.Collections.IDictionary)s.DeserializeObject( example );
var a = (System.Collections.ICollection)o["series"];

foreach( System.Collections.IDictionary d in a )
{
   d["frequency"] = d["f"];
   d.Remove( "f" );
}

string result = s.Serialize( o );

Console.WriteLine( example );
Console.WriteLine( result );

Also add a reference to System.Web.Extensions.

Or better fix the part that generates this string.


Wednesday, July 12, 2017 7:01 AM

Hi SyedF,

The following code shows how to change the 'f' value.

static void Main(string[] args)
        {
            string path = @"C:\Users\v-feih\json.json";          
            string json = File.ReadAllText(path);

            JObject jo = JObject.Parse(json);
            int seriorCount = GetSeriorCount(jo);
            dynamic jsonObj = JsonConvert.DeserializeObject(json);    
            for (int i = 0; i < seriorCount; i++)
            {
                jsonObj["series"][i]["f"] = i;
            }
            string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
            File.WriteAllText(path, output);

        }
        private static int GetSeriorCount(JObject jo)
        {
            foreach (var ab in jo)
            {
                var appName = ab.Key;
                if (ab.Key == "series")
                {
                    return ab.Value.Count();
                }
            }
            return 0;
        }

Result:

If you have any issues,please feel free to contact me.

Best regards,

feih-7

MSDN Community Support.

Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread.If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com


Saturday, January 11, 2020 2:22 AM

Hello @BonnieB, I would like to replace frequency's value (Was: "W") with say "Z".  How do I do that?  Thanks in advance for your help!

Tien

Tien Le


Wednesday, January 15, 2020 6:16 AM

  Well, @Tien, I'm not sure if this is a trick question or not?  ;0) It seems simple enough, given my previous reply.

And, it depends on whether you'd like to replace the "f" with "frequency" or not. Here are both versions:

string replace = test.Replace("\"f\":\"W\"", "\"frequency\":\"Z\"");
replace = test.Replace("\"f\":\"W\"", "\"f\":\"Z\"");

 

And if you'd like to do the replacement and end up with it in the same variable:

test = test.Replace("\"f\":\"W\"", "\"frequency\":\"Z\"");

~~Bonnie DeWitt [C# MVP]

http://geek-goddess-bonnie.blogspot.com