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

AngularUi Mobile Modal List Display

I attempted to implement the code from 32400236/dynamically-generate-modals-with-mobileangularui but encountered issues. I also tried using the following: <div class="access-item" ng-repeat="item in items track by $index"> <a ui-turn-on="$index" ...

Resolve issues with vue js checkbox filtering

As I embark on my Vue journey, I came across some insightful queries like this one regarding filtering with the help of computed(). While I believe I'm moving in the right direction to tackle my issue, the solution has been elusive so far. On my web ...

Ensure that my program is halted until the xmlhttprequest has completed

It seems like I've overcomplicated this problem for myself. In my page, I have 2 XMLHTTPRequests - the first request retrieves data from an API and fills my elements with this data. However, one of the fields in my elements requires a second request t ...

Adjust the size of three panels (left, middle, right) using Javascript, ensuring that the middle panel remains unchanged in size

I am a newcomer to JavaScript and currently working with HTML, CSS, and JS files. I have three panels - left, center, and right - that I want to resize. The left panel resizes correctly when dragging the column border. https://i.stack.imgur.com/LxhUX.png ...

Creating an array of objects in Javascript by setting two different values as a range

Given an array of objects structured as follows: [{value: "a", start: 1950, end: 1954, description: "aaa"}, {value: "b", start: 1953, end: 1956, description: "bbb"}, {value: "c", start: 1960, end: 1962, des ...

Creating a Custom TreeView in VS Code using JSON data

My goal is to create a TreeView using data from a JSON file or REST call, with custom icons for each type of object (Server, Host, and Group). I want to implement configuration.menu similar to the dynamic context menu discussed in this thread. I am relati ...

Collecting information from JSON files

Within the cells of my calendar are placeholders for events, dates, participants, and descriptions. Now, I am looking to populate these placeholders with data previously stored using localStorage. Unfortunately, my current code is not achieving this. How ...

Using percentages to position Div elements

Currently, I am working on an HTML page that requires a div element spanning the full width of the page. My goal is to arrange other divs within this full-width div using percentages rather than pixels. The class associated with this div is .question. Thi ...

Attempting to remove options in a Multiple Choice scenario by selecting the X icon beside each one

I'm working on a multiple choice quiz and I'd like to add a button or icon resembling X in front of each option (even in front of the radio button), so that when I click on it, only that specific option is deleted. How can I achieve this? For in ...

waiting to display information until it is necessary

I am currently working on optimizing my website for improved loading speed and responsiveness. Users can scroll through up to 4k images, apply filters, and sort them based on their preferences. Below is the code snippet for my filtering function: function ...

Using the Table-multiple-sort feature in boostrap-table is not functioning properly when there are multiple tables present on a single page

I have implemented bootstrap-table along with the extension table-multiple-sort. The issue I am facing is when I include two tables on a single page (with the second table within a modal window), the multisort feature does not seem to work on the second ta ...

React Native Issue: Missing propType for native property RCTView.maxHeight

Upon upgrading to RN 0.30, I encountered the error message below even when trying to build the most basic app: react-native init AwesomeProject react-native run-ios What's peculiar is that the warnings include components BlurView, VibrancyView, an ...

How can I move a TableItem from one material UI component to another using drag-and-drop?

I am facing an issue where I need to drag a ListItem from one List component to another. I am uncertain about how to accomplish this in Material UI. ...

Form an object using elements of a string array

Trying to convert a string array into an object. The string array is as follows : let BaseArray = ['origin/develop', 'origin/master', 'toto/branch', 'tata/hello', 'tata/world']; I want the resulting obje ...

What is the method to retrieve the string value from a JavaScript String object?

Is there a way to extend a method to the String prototype and manipulate the string value? I'm facing some difficulty in accessing the actual string value, as this, the current object context, seems to refer to the string object instead. String.pro ...

Is it possible to use the same identifier for both the name and id attributes in HTML?

In the world of coding, the "name" attribute is often used in server-side programming to send name/value pairs in requests. On the other hand, the "id" attribute is commonly utilized in client-side programming such as Javascript and CSS. However, both att ...

Error encountered during the building of a Java project using Gradle

I ran into an issue with Git Bash error output (build failed). Despite attempting to resolve it by installing Python as suggested, setting the Python environment variable in IntelliJ, and following other recommendations, I still encounter the same build ...

Issues with the node.js and discord.js API due to superagent integration

Hey there, I've been working with an API that provides information based on ID inputs. Everything was running smoothly until I encountered an issue with invalid IDs. Instead of displaying a message like Invalid ID, my bot crashes when a wrong ID is en ...

NodeJS allows for the dynamic import of modules, enabling a flexible

I'm currently developing a CLI package within a monorepo that contains a command called buildX. This command goes through various directories, attempting to use the require function to locate a module within certain files in those directories. In ess ...

Triggering a keyboard *ENTER* event on an Input in Javascript/React by clicking a button is a common query among developers

I am facing a challenge with an Input element that only displays results when I press Enter on the keyboard. The element is part of a third-party extension, so my control over it is limited. My goal is to trigger the ENTER event for the Input when a button ...