-3

I would like to modify the values AREA1 & AREA2 from the parsed JObject of the below JSON string.

How can I retrieve the elements with jObject.SelectTokens() and edit it them?

{
   "summary":{
      "summaryDataTable":{
         "id":"summaryDataTable",
         "type":"dataTable",
         "source":"/SmartScreen/SummaryFw",
         "columns":[
            {
               "name":"CreateDate",
               "title":"AREA1",
               "filterable":false
            },
            {
               "name":"CreateUser",
               "title":"AREA2",
               "filterable":false
            }
         ],
         "options":{
            "showFilter":false
         }
      }
   }
}
dbc
  • 104,963
  • 20
  • 228
  • 340
Orhano95
  • 77
  • 9
  • Related: [Replace part of a JSON with other (using a string token)](https://stackoverflow.com/q/33045235/3744182). – dbc Oct 09 '21 at 01:26

2 Answers2

4

If you just need to modify it for the above JSON model, use JObject.SelectToken to get the parent objects using the JSON path & then set the value like below:

var data = JObject.Parse(json);

var firstColumn = data.SelectToken("summary.summaryDataTable.columns[0]");
var secondColumn = data.SelectToken("summary.summaryDataTable.columns[1]");
firstColumn["title"] = "replacedTitle1";
secondColumn["title"] = "replacedTitle2";

Output:

{
  "summary": {
    "summaryDataTable": {
      "id": "summaryDataTable",
      "type": "dataTable",
      "source": "/SmartScreen/SummaryFw",
      "columns": [
        {
          "name": "CreateDate",
          "title": "replacedTitle1",
          "filterable": false
        },
        {
          "name": "CreateUser",
          "title": "replacedTitle2",
          "filterable": false
        }
      ],
      "options": {
        "showFilter": false
      }
    }
  }
}
Ermiya Eskandary
  • 15,323
  • 3
  • 31
  • 44
0

You can try this

var json= ...your json;

var o= JObject.Parse(json);
var columns=o.SelectToken("summary.summaryDataTable.columns");

columns[0]["title"]="newTitle1";
columns[1]["title"]="newTitle2";

json = o.ToString(Newtonsoft.Json.Formatting.Indented);
Serge
  • 40,935
  • 4
  • 18
  • 45