0

No idea where to begin with this, so I don't have any sample code.

I need to change the name of a property in a json document.

var json = (@"{""id"":""12"",
   ""title"":""My Title"",
   ""Chunks"":[ 
      { 
         ""id"":""137"",
         ""title"":""Title"",
         ""description"":""null"",
         ""selections"":[ 
            { 
               ""id"":""169"",
               ""title"":""Choice"",
               ""sort_order"":""null"",
               ""questions"":[ 
               ]
            }
         ]
      }
   ]
}
}
}");

I need to change the "id" that's got the value of 12 to "document_id" and leave the other ids alone. Are there any C# libraries like NewtonSoft that allow you to change the property rather than the property value. Seems like a common scenario but I haven't seen anything close to what I'm trying to do. I suppose I could convert the json to a string and do a replace, but that doesn't seem very elegant.

Intrepid2020
  • 161
  • 1
  • 9
  • 1
    [This is the droid you are looking for](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Serialization_JsonProperty.htm) – Ňɏssa Pøngjǣrdenlarp Oct 30 '19 at 15:03
  • 1
    See https://stackoverflow.com/questions/16181298/how-to-do-recursive-descent-of-json-using-json-net which explains how to walk a JSON object and perform actions on it. – Ian Mercer Oct 30 '19 at 15:03
  • 1
    See also: [Rename JProperty in json.net](https://stackoverflow.com/q/47267542/10263) – Brian Rogers Oct 30 '19 at 16:21

2 Answers2

1

An approach using Newtonsoft.Json.Linq.JObject would look something like:

var obj = JObject.Parse(json);
obj["document_id"] = obj["id"]; // create new property called "document_id"
obj.Remove("id"); // remove the "id" property
Console.WriteLine(obj);

Also note that your JSON is not valid. It has two extra } at the end.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

Assuming you would want to replace all the keys when there could be more than one node with key as "id" and value "12", you could use Linq to identify Tokens with Key "Id" and Value "12" and then use Add/Remove methods for creating a new node with different name.

For example,

JToken node = JToken.Parse(json);
var jObjectsWithTitle = node
    .SelectTokens("$..*")
    .OfType<JObject>()
    .Where(x => x.Property("id") != null &&  Convert.ToInt32(x.Property("id").Value) == 12);

foreach(var item in jObjectsWithTitle)
{
        item.TryGetValue("id",out var currentValue);
        item.Add("document_id",currentValue);
        item.Remove("id");
}
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51