Reputation: 77
I have returned two objects as json through ajax. Now i'm unable to access the values in these two lists. Earlier i had one list and i was able to parse it easily.
data=serialize("json", vm_obj)
data2=serialize("json", user_networks_list)
data_dict["vm"] = vm_obj
data_dict["nt"] = user_networks_list
json = simplejson.dumps({'vm': data, 'nt': data2})
return HttpResponse(json, mimetype='application/javascript')
So, i have to lists names nt and vm. and my returned json looks like.
{"nt": "[{"pk": 1, "model": "network.defaultnetwork", "fields": {"endip": "100.16.10.255", "subnet": "100.16.10.0/24", "startip": "100.16.10.25", "port_group": "RoyalTech-803-pg", "is_default": 1, "eth_interface": "eth1", "dnsname": "royaltech.net", "user": 803, "dns": "172.16.10.1", "networkname": null, "gateway": "100.16.10.1"}}, {"pk": 241, "model": "network.defaultnetwork", "fields": {"endip": "100.168.5.254", "subnet": "100.168.5.0/24", "startip": "100.168.5.25", "port_group": "RoyalTech-803-pg1", "is_default": 0, "eth_interface": "eth2", "dnsname": "latest.local", "user": 803, "dns": "8.8.8.8", "networkname": "maxcheck", "gateway": "100.168.5.1"}}, {"pk": 2, "model": "network.defaultnetwork", "fields": {"endip": "10.250.0.254", "subnet": "10.250.0.0/24", "startip": "10.250.0.25", "port_group": null, "is_default": 0, "eth_interface": "eth3", "dnsname": "testing network", "user": 803, "dns": "100.0.0.0", "networkname": "Testing network", "gateway": "100.111.0.1"}}]", "vm": "[{"pk": 700, "model": "virtualmachine.virtualmachines", "fields": {"guest_full_name": "Windows_server_2008_R2_x86_64", "remoting": true, "vm_path_name": "/v/Roya-hd28_1.img", "user_type": null}}]"}
Earlier I had one list and i was able to access the data in a loop using following javascript.
for (var i = 0; i < data.length; i++)
{
visitors = data[i].pk;
object = data[i]['fields'].name;
}
Any ideas what the javascript would look like now?
Upvotes: 1
Views: 192
Reputation: 4136
You have two lists in your new data object now, so you'd do something like this:
for (var i = 0; i < data.vm.length; i++) {
visitors = data.vm[i].pk;
object = data.vm[i]['fields'].name;
}
for (var j = 0; i < data.nt.length; j++) {
visitors = data.nt[j].pk;
object = data.nt[j]['fields'].name;
}
Upvotes: 0
Reputation: 598
Hope this helps
var vm = data.getAt('vm');
var nt = data.getAt('nt');
Now run the same loop you used before on vm and nt.
Thanks
Upvotes: 0
Reputation: 599856
You're double-encoding the JSON in the sub-dicts. You should serialize to Python dicts first, then dump the whole lot to JSON only at the end:
data=serialize("python", vm_obj)
data2=serialize("python", user_networks_list)
data_dict["vm"] = vm_obj
data_dict["nt"] = user_networks_list
json = simplejson.dumps({'vm': data, 'nt': data2})
Upvotes: 1