Hi
I want to remove outer json array in c#. please help
Input JSON
[{
"result1": [{
"number": "string",
"id": "string"
}]
},
{
"result2": [{
"number": "string",
"id": "string"
}]
}]
[Output JSON]
{
"result1": [
{
"number": "string",
"id": "string"
}
],
"result2": [
{
"number": "string",
"id": "string"
}
]
}


Mohammad HussainRank #513 · 4.8K reputationPosted Aug 21, 2023, 8:02 AM EDT
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; namespace RemoveOuterJsonArray { class Program { static void Main(string[] args) { string inputJson = @" [ { ""result1"": [ { ""number"": ""string"", ""id"": ""string"" } ] }, { ""result2"": [ { ""number"": ""string"", ""id"": ""string"" } ] } ]"; JArray inputArray = JArray.Parse(inputJson); JObject outputObject = new JObject(); foreach (var item in inputArray) { foreach (var property in item.Children()) { outputObject[property.Name] = property.Value; } } string outputJson = outputObject.ToString(Formatting.Indented); Console.WriteLine(outputJson); } } }Amit MohantyRank #112 · 20K reputationPosted Aug 21, 2023, 6:52 AM EDT
To remove the outer JSON array in C#, you can use a JSON library like Newtonsoft.Json
string inputJson = @" [{ ""result1"": [{ ""number"": ""string"", ""id"": ""string"" }] }, { ""result2"": [{ ""number"": ""string"", ""id"": ""string"" }] }]"; JArray jsonArray = JArray.Parse(inputJson); JObject outputObject = new JObject(); foreach (JObject item in jsonArray) { foreach (var property in item.Properties()) { outputObject.Add(property.Name, property.Value); } } string outputJson = outputObject.ToString(Formatting.Indented); Console.WriteLine(outputJson);Deepak RawatRank #646 · 3.7K reputationPosted Aug 21, 2023, 8:02 AM EDT
You want to remove the outermost JSON array from the input JSON and keep the inner objects intact. You can achieve this by parsing the input JSON, extracting the inner objects, and creating a new JSON object with those inner objects.
using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; class Program { static void Main() { string inputJson = "[{\"result1\":[{\"number\":\"string\",\"id\":\"string\"}]},{\"result2\":[{\"number\":\"string\",\"id\":\"string\"}]}]"; JArray jsonArray = JArray.Parse(inputJson); JObject outputJson = new JObject(); foreach (JObject obj in jsonArray) { foreach (KeyValuePair property in obj) { outputJson[property.Key] = property.Value; } } Console.WriteLine(outputJson.ToString(Formatting.Indented)); } }Cr BhargaviRank #420 · 5.9K reputationPosted Aug 23, 2023, 9:22 AM EDT
Please use the Newtonsoft.Json library for removing outer json array in c#