Search code examples
c#arraysjsonstreamwriter

How to update/modify values in Json File


I want to update values in the following type of json file in c#

{"ItemName":"ABC","Id":1}
{"ItemName":"DEF","Id":2}
{"ItemName":"GHI","Id":3}
{"ItemName":"ABC","Id":1}
{"ItemName":"JKL","Id":2}
{"ItemName":"MNO","Id":3}

How can i remove duplicate values based on 'ItemName' and than update Id. Like expected output will be:

{"ItemName":"ABC","Id":1}
{"ItemName":"DEF","Id":2}
{"ItemName":"GHI","Id":3}

{"ItemName":"JKL","Id":4}
{"ItemName":"MNO","Id":5}

I searched alot about json.writer function but couldn't found a solution for a file without using [] and , seperation.

However i can read the file by using below code

var jsonReader = new JsonTextReader(new StringReader(File.ReadAllText("path")))
    {
        SupportMultipleContent = true
    };
var jsonSerializer = new JsonSerializer();

dynamic data = jsonSerializer.Deserialize(jsonReader);

while (jsonReader.Read())
        {                       
            String Items_name = data.ItemName;
        }

Solution

  • You have a class to deser to:

    public record X(string ItemName, int Id);
    

    You read your file deser'ing each line:

    var xs = File.ReadAllLines("path").Select(l => JsonConvert.DeserializeObject<X>(l)).ToList();
    

    You remove your duplicates:

    var deduped = xs.DistinctBy(x => x.ItemName);
    

    and perform your other manipulations etc (maybe you will want to call ToList on the above). Then you reserialize:

    File.WriteAllLines("path", deduped.Select(x => JsonConvert.SerializeObject(x)).ToArray());