Using JavaScript in Ext JS 4, transform a JSON object into a different JSON object

What is the simplest way to transform JSON A into JSON B using JavaScript?

JSON A:

{
    "d":
    [
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"0","value":"one"},
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"1","value":"two"},
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"2","value":"three"}
    ]
}

JSON B:

{
    data:
    [
        {"key":"1", "value":"one"},
        {"key":"2", "value":"two"},
        {"key":"3", "value":"three"}
    ]
}    

===================

Update on 8/1/2012 (solution for Ext JS with ASP.NET proxy):

I didn't mention the JavaScript framework I was using in my original question, but it appears that by setting the root property value to "d" you can effectively remove the "d" key.

var statusDropdownStore = new Ext.data.Store({
    proxy: new Ext.ux.AspWebAjaxProxy({
        url: '/track/Controls/Shared/GeneralService.asmx/GetDropdownOptions',
        actionMethods: {
            create: 'POST',
            destroy: 'DELETE',
            read: 'POST',
            update: 'POST'
        },
        extraParams: {
            user_login: authUser,
            table_name: '[status]'
        },
        reader: {
            type: 'json',
            model: 'DropdownOption',
            root: 'd'
        },
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        }
    })
});

Proxy:

Ext.define('Ext.ux.AspWebAjaxProxy', {
    extend: 'Ext.data.proxy.Ajax',
    require: 'Ext.data',

    buildRequest: function (operation) {
        var params = Ext.applyIf(operation.params || {}, this.extraParams || {}),
                                request;
        params = Ext.applyIf(params, this.getParams(params, operation));
        if (operation.id && !params.id) {
            params.id = operation.id;
        }

        params = Ext.JSON.encode(params);

        request = Ext.create('Ext.data.Request', {
            params: params,
            action: operation.action,
            records: operation.records,
            operation: operation,
            url: operation.url
        });
        request.url = this.buildUrl(request);
        operation.request = request;
        return request;
    }
});

Combo Box (dropdown) configuration:

                    {
                        xtype: 'combo',
                        fieldLabel: 'Status',
                        emptyText: 'Select a status...',
                        store: statusDropdownStore,
                        valueField: 'key',
                        displayField: 'value',
                        mode: 'remote',  // or 'local'
                        renderTo: document.body
                    },

Answer №1

Below is an example:

var sample = {
    "info":
    [
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"0","value":"apple"},
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"1","value":"banana"},
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"2","value":"orange"}
    ]
};

sample.data = sample.info;
delete sample.info;
for(var j=0,n=sample.data.length;j<n;j++){
    delete sample.data[j].__type;
}

Answer №2

Here is a possible solution:

var parsedJson = JSON.parse(JsonA);
parsedJson = parsedJson.d;

var newJson = [];
var newObj = {};

if (parsedJson.length > 0) { 

  for (var i = 0, loopTimes = parsedJson.length; i < loopTimes; i++) {
      newObj = {};
      newObj.key = parsedJson[i].key;
      newObj.value = parsedJson[i].value;
      newJson.push(newObj);
  }
}

parsedJson = null; // if you need to discard the initial object

In addition, I believe JsonB should be an array of objects, rather than an object containing an array of objects like this:

[
     {"key":"1", "value":"one"},
     {"key":"2", "value":"two"},
     {"key":"3", "value":"three"}
]  

Answer №3

If you're facing this issue, you can consider following the steps mentioned in - which involves utilizing the delete function to eliminate the key.

One approach is to iterate through the array and apply the delete method, followed by renaming the array (by introducing a new attribute and then removing the old one).

Answer №4

give this a shot :) http://jsfiddle.net/daewon/LnpXb/

var jsonData = {
    items: [
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"0","value":"apple"},
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"1","value":"banana"},
        {"__type":"Web.Controls.Shared.GeneralService+DropdownKeyValuePair","key":"2","value":"cherry"}
   ]
};

var newData = {
    data: []
};

var items = jsonData.items;
for (var j=0; j<​items.length​; j++){
    var object = {
        key : items[j].key,
        value : items[j].value
    };

    newData.data.push(object);    
}
console.log(JSON.stringify(newData));
=> {"data":[{"key":"0","value":"apple"},{"key":"1","value":"banana"},{"key":"2","value":"cherry"}]} 

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

Utilizing Flask for analyzing characteristics of text presented in JavaScript

My current variables consist of: myfruits = ['Apple', 'Banana', 'Lemon'] havefruit = [True, True, False] If the user input changes the values in havefruit, I need to implement JavaScript in my HTML file to display the entrie ...

Output the ID of each completed task from the JSON file using a bash script

Here is an example of a Json file: { "tasks": [ { "id": "nightly_1652299200", "repo": "tx/tx5", "branch": "dev", "type": "HealthCheck", ...

Delete Entries in MongoDB Collection According to Unique User Pairs

I have a collection of messages stored in MongoDB and I need to keep only the latest 500 records for each pair of users. Users are identified by their sentBy and sentTo attributes. /* 1 */ { "_id" : ObjectId("5f1c1b00c62e9b9aafbe1d6c&quo ...

What is the best way to structure my POST data when conducting tests on an express API endpoint?

I have been exploring the MERN stack with the help of this guide: https://www.digitalocean.com/community/tutorials/getting-started-with-the-mern-stack. Currently, I am trying to test a POST API endpoint that is built using express. The node server is up ...

Angular is throwing a RangeError due to exceeding the maximum call stack size

Encountering a stackOverflow error in my Angular app. (see updates at the end) The main issue lies within my component structure, which consists of two components: the equipment component with equipment information and the socket component displaying conn ...

How does the interaction between Express and Angular for routing in the MEAN Stack function?

Currently, I am utilizing Express static to direct to the public directory. //app.js app.use(express.static( __dirname + '/public')); I am looking for a way to have most of the UI routing done by AngularJS. However, it seems that it only works ...

What is preventing me from using GET to pass parameters to WebMethod?

Here is an example of how my WebMethod is structured: [WebMethod] [ScriptMethod(ResponseFormat=ResponseFormat.Json, UseHttpGet=true)] public List<Person> Greetings(string greeting) { List<Person> individuals = new List<Person> { ...

Currently, I am encountering a problem as I attempt to iterate through a dynamic table

I have a table containing various elements. An example row is Jack Smith with multiple rows like this: col1 col2 col3 col4 col5 col6 col7 col8 jack smith 23 Y Y error error_code error_desc The table is ...

Is it Better to Transform JSON Data into a Contract or a Class

Is there a tool or software that can analyze a sample JSON response and create a serializable class or contract? I am struggling to convert a moderately sized JSON structure into a contract, but I have access to a sample response. The JSON response inclu ...

Tips for including headers with @Url.Action() to enable jwt authorization

When a user inputs correct login credentials, they should be redirected to the next page (LandingPage). However, upon clicking the Submit button, users are receiving a 401 unauthorized error instead of being directed to the next page. The JWT token is gene ...

Issues with hover functionality in Javascript, CSS, and HTML

Seeking assistance with my JavaScript, HTML, and CSS development, I ran into an issue while trying to create a hovering function for my webpage. Despite my efforts, the links are not displaying anything when hovered over, and the divs meant for specific ho ...

issue with integrating promise in angular 4

I'm currently learning about promises and how to implement them in Angular. I have written the following code in StackBlitz. My goal is to display the array whenever it contains a value by using promises in Angular. This is my HTML code: <h2>A ...

Choose a looping function in React JS that iterates over an array of objects

I have an array of objects let arr = [0: {received: "Return Received", approved: "Approved", rejected: "Rejected"} 1: {authorized: "Authorized", received: "Return Received"}} I am looking to populate a < ...

Volley JSON Exception: Unexpected end of data at position 0

I have encountered a problem while trying to utilize Volley for REST calls. Specifically, when attempting to make a Put call with a JSON Object as a parameter, I am receiving an error message stating: error with: org.json.JSONException: End of input at cha ...

transforming information from a database into JSON using CodeIgniter

I'm having trouble retrieving data from the database and converting it into JSON using Codeigniter. Here is my database structure: create table todolist( todo_id int, todo_content text ) And here are some examples of entities in the database: 1 ...

Most Effective Method for Switching CSS Style Height from "0" to "auto"

After coming across a question with no answer that suited my needs, I decided to share the solution I created. In my case, I had a hidden generated list on a page which was initially set with a CSS height of "0" and then expanded upon clicking by transit ...

Question: How can I use the jQuery datepicker to ensure that the selected date remains in the

I recently created a webpage using a combination of HTML, PHP, and jQuery. The PHP script is designed to load all data where the date matches the one selected in the text input field generated by the jQuery datepicker. However, I encountered a problem whe ...

Reading various JSON files in Objective C

In short, I need to access only the parent element in the JSON file. How to parse multiple JSON in Objective-C?) I am trying to extract the author > NAME from this JSON. The code for this task is as follows: NSURL *blogURL = [NSURL URLWithString:@"*remov ...

include the ReactToastify.css file in your project using the import statement

Error in file path C:\Users\User\Documents\GitHub\zampliasurveys_frontend\node_modules\react-toastify\dist\ReactToastify.css:1 ({"Object.":function(module,exports,require,__dirname,__filename,jest){:ro ...

Struggling with parsing specific values in JSON file while trying to improve Python skills

Embarking on my first Python project focusing on Stardew Valley and its crop prices has been an exciting challenge. For those familiar with the game, you may know that each shop sells unique items, creating a diverse market. I am currently working with a ...