简体   繁体   中英

Unnest a JSon Object returned from api

How can I remove the nested json object returned from an api as shown below and show it as individual fields by unnesting the object using jquery in a generic way. here is my json object

 "response": {
"content": 
"[ {    
      "Id": 0,    
     "Name": "Some name",    
     "createdOnDate": "0001-01-01T00:00:00",      
    "keyValueList": 
      [      
           {        
             "Key": "key1",        
            "Value": "Sample Data key 1"      
            },      
           {        
            "Key": "key2",        
           "Value": "sample data key 2   
      ] }]"

this is how it should be after unnesting.

[{
    "Id": 123,
        "Name": "some name",
        "createdOnDate": "2013-01-22T17:02:00",
        "key1": "this is my key1",
        "key2": "this is my key2"

}]

This is invalid JSON. Make sure you're getting valid before. Afterwards you can iterate through the attributes and set them the way you want.

$.each(content[0]['keyValueList'], function (k, value) {
    content[0][value['Key']] = value['Value']
});

delete content[0]['keyValueList'];

http://jsfiddle.net/TjQzv/3/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM