5

What is the easiest way to convert JSON A to 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"}
    ]
}    

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

8/1/2012 update (answer when using Ext JS and you have an ASP.NET proxy:

I didn't provide this in my question about what I'm using for a JavaScript framework, but it turns out you can implicitly eliminate the "d" key by specifying the value "d" in the root property

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
                    },
JustBeingHelpful
  • 18,332
  • 38
  • 160
  • 245

4 Answers4

2

Here's a sample

var old = {
    "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"}
    ]
};

old.data = old.d;
delete old.d;
for(var i=0,l=old.data.length;i<l;i++){
    delete old.data[i].__type;
}
sissonb
  • 3,730
  • 4
  • 27
  • 54
1

You could try the solution outlined at https://stackoverflow.com/a/1219633/832457 - using delete to remove the key.

Try looping through the array and using delete, then rename the array (by creating a new attribute and the deleting the old one

Community
  • 1
  • 1
1

I think this would do it:

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

var TheJsonB = {};
TheJsonB.data = [];
var TheObject = {};

if (TheJsonA.length > 0) { 

  for (var i = 0, LoopTimes = TheJsonA.length; i < LoopTimes; i++) {
      TheObject = {};
      TheObject.key = TheJsonA[i].key;
      TheObject.value = TheJsonA[i].value;
      TheJsonB.data.push(TheObject);
  }
}

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

I also this JsonB shouldn't be an object that contains an array of objects; I think it should just be an array of objects like this:

[
     {"key":"1", "value":"one"},
     {"key":"2", "value":"two"},
     {"key":"3", "value":"three"}
]  
frenchie
  • 51,731
  • 109
  • 304
  • 510
  • you are precisely right about only having the array as the object! See the bottom of my question in regards to how ExtJS allows you to remove the "d" property. I guess the "__type" property stays there.. doesn't hurt anything since we explicitly state the "key" and "value" in the combo configuration. – JustBeingHelpful Aug 01 '12 at 16:21
  • "key" being the valueField value property and "value" being the displayField value – JustBeingHelpful Aug 01 '12 at 16:23
  • Yes, you can use ExtJS to extract the array from the wrapping object but that's heavy artillery! The second line of code does it by reassigning the elements inside .d to the wrapping object itself: TheNewObject = TheNewObject.d; Happy coding!! – frenchie Aug 01 '12 at 19:05
  • Have you ever eaten at Frenchies on Clearwater Beach? (near Tampa/St. Petersburg) Great Food! – JustBeingHelpful Aug 01 '12 at 20:26
  • 1
    No, but have you ever eaten in Paris, France? – frenchie Aug 01 '12 at 20:30
  • Nope, but I once ate in Lourdes when I was 10. I remember they served my milk with ice because I asked for it cold. – JustBeingHelpful Aug 01 '12 at 20:38
  • I guess that's kinda like using ExtJS to extract a property from an object. Good luck with your programming. – frenchie Aug 01 '12 at 20:59
1

try this :) http://jsfiddle.net/daewon/LnpXb/

var jsonA = {
    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"}
   ]
};

var jsonB = {
    data: []
};

var d = jsonA.d;
for (var i=0; i<​d.length​; i++){
    var obj = {
        key : d[i].key,
        value : d[i].value
    };

    jsonB.data.push(obj);    
}
console.log(JSON.stringify(jsonB));
=> {"data":[{"key":"0","value":"one"},{"key":"1","value":"two"},{"key":"2","value":"three"}]} 

blueiur
  • 1,447
  • 1
  • 11
  • 17