Alter the configuration of a JSON object

I'm currently working on modifying the following JSON text. It has the structure as shown below:

  {
  "cabecera": {
    "tipo_cambio": "",
    "fecha_emision": "",
    "total": ""
  },
  "detalle": {
    "940b130369614bd6b687dc5b41623439": {
      "producto": "94115891",
      "detalle_adicional": "",
      "cantidad": "",
      "precio_unitario": "",
      "subtotal": "",
      "total": ""
    },
    "6cbdcef2bbff4b059c8de7432c9aa5f2": {
      "producto": "6738756",
      "detalle_adicional": "",
      "cantidad": "",
      "precio_unitario": "",
      "subtotal": "",
      "total": ""
    }
  }
}

My goal is to transform it into the following structure where unique codes like "940b130369614bd6b687dc5b41623439" are removed, and detalle becomes an array:

{
  "cabecera": {
    "tipo_cambio": "",
    "fecha_emision": "",
    "total": ""
  },
  "detalle": [
    {
      "producto": "94115891",
      "detalle_adicional": "",
      "cantidad": "",
      "precio_unitario": "",
      "subtotal": "",
      "total": ""
    },
    {
      "producto": "6738756",
      "detalle_adicional": "",
      "cantidad": "",
      "precio_unitario": "",
      "subtotal": "",
      "total": ""
    }
  ]
}

Is there a way to achieve this using C#?

Answer №1

Below is a brief C# script that tackles the issue

string originalJson =
@"{
""header"": {
    ""exchange_rate"": """",
    ""emission_date"": """",
    ""total"": """"
},
""details"": {
    ""940b130369614bd6b687dc5b41623439"": {
    ""product"": ""94115891"",
    ""additional_details"": """",
    ""quantity"": """",
    ""unit_price"": """",
    ""subtotal"": """",
    ""total"": """"
    },
    ""6cbdcef2bbff4b059c8de7432c9aa5f2"": {
        ""product"": ""6738756"",
        ""additional_details"": """",
        ""quantity"": """",
        ""unit_price"": """",
        ""subtotal"": """",
        ""total"": """"
    }
}
}";

JObject obj = JObject.Parse(originalJson);
JArray detailsChildren = new JArray(obj.SelectToken("details").Select(x => x.Children()));

obj.Remove("details");
obj.Add("details", detailsChildren);

Console.WriteLine(obj);

To implement this code, make sure you have installed the Newtonsoft.Json NuGet package

<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Explore the world of threejs with a sphere adorned with cube bumps

Currently, I am navigating through the internet in search of a solution for my problem. The example I came across is quite impressive, take a look: . My dilemma lies in converting these squares into CSS cubes while ensuring that they do not get cut off by ...

I'm looking to leverage axios and useState-useEffect to collect data from numerous web pages. Any suggestions on how to do this efficiently

I stumbled upon a URL that leads to an API with a total of 42 pages and 826 data entries. The URL is . My goal is to store all the data in one variable for future filtering purposes, especially when implementing a "show more" button feature. Initially, on ...

When implementing Critical CSS, the Jquery function fails to execute upon loading

Currently, I am working on optimizing my website at . In an attempt to improve its performance, I decided to implement critical CSS using penthouse. The Critical CSS code can be found here, generously provided by the main developer of penthouse. However, ...

i am trying to execute a function in an angularjs controller through html, but the scope variable that i am

Being new to angularjs, I'm looking to understand the process of calling a function defined in a controller from HTML within angularjs. I have written the following code in my HTML: First.html <input type="text" ng-model="model.name" name="name ...

Using the fetch/await functions, objects are able to be created inside a loop

In my NEXTJS project, I am attempting to create an object that traverses all domains and their pages to build a structure containing the site name and page URL. This is required for dynamic paging within the getStaticPaths function. Despite what I believe ...

Struggling with implementing conditional validators in Angular2 form models. I have tried using myForm.setValidators(), but it doesn't appear to be functioning as expected

I have been experimenting with the model form in an Ionic/Angular2 project. My goal is to implement conditional validation on a form where users initially fill out 6 required fields, and then choose between 'manual' and 'automatic' proc ...

Is there a way to display the button solely when the cursor is hovering over the color?

When I hover over a particular color, I want the button to show up. However, instead of displaying the button only for that color, it appears for all the colors of the product. Also, the placement of the button on the left side means that if I try to hover ...

Guide on updating a MongoDB document upon clicking a button on an HTML page

I'm new to backend development and I've been working on creating a CRUD notes application without using React or EJS. My current issue is that I am unable to edit documents. The desired functionality is for the user to be directed to a page wher ...

When the Enter key is pressed while in an input element within a child component, it triggers a method that was originally defined in the parent component as well

In my application, there is a parent component that allows users to select skills from a list of options. Additionally, there is a child component where users have the ability to add their own skill if it is not available in the parent component. The chal ...

How can we compress videos on an Android device prior to uploading them through a web browser?

Can video compression be done prior to uploading via a web browser? For example, in iOS devices you can choose a video using the HTML input type file tag and iOS will automatically compress it before uploading. Are there any JavaScript or jQuery libraries ...

What is the best way to retrieve the value of a button using javascript?

After trying to extract the value from a button in JavaScript, here is the code I used: for(i=0; i<cars.length;i++){ var p = `<button id="myBtn" onclick="myFunction()" value="${cars[i]}">${cars[i]}</button>` func ...

How do I customize the HOME page in JHipster to display unique content based on user roles?

I am currently developing a JHipster project where I need to display different home pages based on the role of the user logging in. Specifically, I am utilizing Angular 1.x for this project. For instance, I have roles such as ROLE_ADMIN and ROLE_USER, each ...

Creating randomized sequences using JavaScript

One of my hobbies involves organizing an online ice hockey game league where teams from different conferences compete. It's important to me that every team gets an equal number of home and away matches throughout the season. To simplify this task, I&a ...

Ways to keep selected values in the Select box without unchecking them again?

Hello there, I am relatively new to ReactJS and currently facing an issue with Selects. Specifically, I have a Select component that displays a list of names using MenuItem. My goal is to have certain names pre-selected in the Select dropdown upon initial ...

Mixing box-shadow and blur filters can result in unusual artifacts appearing in Webkit browsers

Recently, I encountered an intriguing and frustrating bug in WebKit browsers. Consider a scenario where there is a parent DIV (let's say .wrapper) and a child DIV (.main). You apply a box-shadow on the .main DIV and a blur filter on the .wrapper DIV. ...

What is the proper way to safely escape a JSON string for an object that contains user-generated content?

How can I correctly use the variable s for the value-field of an option-element while escaping user input used for key and value? var key='highway'; var value='track'; var s = JSON.stringfy({ [key]:value }, undefined,''); s ...

Utilize various addMethods on a field in the event a radio button is chosen through the jQuery validator plugin

When a specific radio button value is selected, I need to apply different methods to a single field. If "true" is selected, method X should be applied. If "false" is selected, method Y should be used on the same field. I attempted to achieve this with a ...

Influencing location preferences in Google's place search

I'm currently implementing a Google Places search feature and I need to enable "Location Biasing" for the GCC countries (UAE, Saudi Arabia, Oman, Kuwait & Bahrain). My goal is to achieve the functionality described in the following link: https://deve ...

I'm struggling to interpret the reply received from $.ajax

Looking to make adjustments to my existing code in order to add comments for images that are fetched using $.ajax and returned as html. The plan is to retrieve the comments as a JSON object, and then parse the previously obtained HTML to insert the commen ...

I'm looking for a solution to correct the array output from my function in node

I have a function that is currently functioning, but I am in need of proper array sorting. First, I will display my code, followed by the current output and then the desired output. Can someone help me edit my entire code and output? var app = require(&a ...