简体   繁体   中英

How to format json parent child array for json parsing

Trying to parse the below json output using jquery but the problem that I encountering iswhen trying to parse "pprice" for example an "undefined" error is outputted

{ "response": [ {"instances": [ { "instanceID": "000001", "instanceOS": "FreeBSD", "instanceVersion": "10.0", "instanceVendor": "rax", "instanceVendorID": "e28f50b0-7a94-4161-a758-36010c69c8ce", "instanceBit": "64", "instanceSize": "", "instanceEnable": "1", "instanceImg": "fbsd.png" } ], "pricing": [ { "pid": "000001", "pvendor": "rax", "pcpu": "1", "pram": "512MB", "pdisk": "20", "pprice": "0.022", "pband": "", "pssd": "" } , { "pid": "000002", "pvendor": "rax", "pcpu": "1", "pram": "1GB", "pdisk": "40", "pprice": "0.06", "pband": "", "pssd": "" } , { "pid": "000003", "pvendor": "rax", "pcpu": "1", "pram": "2GB", "pdisk": "80", "pprice": "0.12", "pband": "", "pssd": "" } ], "instances": [ { "instanceID": "000002", "instanceOS": "Amazon Linux", "instanceVersion": "2014.03.1", "instanceVendor": "aws", "instanceVendorID": "ami-fb8e9292", "instanceBit": "64", "instanceSize": "", "instanceEnable": "1", "instanceImg": "aws.png" } ], "pricing": [ { "pid": "000004", "pvendor": "aws", "pcpu": "1", "pram": "512MB", "pdisk": "20", "pprice": "0.02", "pband": "", "pssd": "" } , { "pid": "000005", "pvendor": "aws", "pcpu": "1", "pram": "1.7GB", "pdisk": "40", "pprice": "0.06", "pband": "", "pssd": "" } ] } ] }

Can successfully parse instance parameters "instanceOS, InstanceVendor" etc, but get undefined with anything inside the "pricing" arrays.

var flavors = $.parseJSON(data);

//DISPLAY ELEMENT
$('.distros_bx').fadeIn('slow');//

 //FOREACH LOOP
 $(flavors.response).each(function(i,el) {

 var new_flavor = '<div class="os-id">' + el.instanceID + '</div><div class="os">' +   el.instanceOS + '</div><div class="os-version">' + el.instanceVersion + '</div><div class="os-bit">' + el.instanceBit + '-bit</div><div class="prices_bx">' + el.pprice + '</div>';

$('.distros_bx').append(new_flavor);

 });

JSON is valid but perhaps it is not formatted corrected for desired results... Thanks in advance!

This is not a good json, your $(flavors.response).each traverses this:

{
   "response":[
      {
         "instances":[],
         "pricing":[],
         "instances":[],
         "pricing":[]
     }
   ]
}

You have repeated keys of instances and pricing. Besides, while instanceID info is inside instances, pprice info is inside pricing

After going in circles for 2.5 days decided this json was to ridiculous so opted for a simpler solution. Now using two seperate json resultsets one for instances and the other for pricing. Thank you all for the help!

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