我有这样的json:
balancer:"[
"2", {"balancer_upload": 0,
"balancer_upload_speed": -120,
"balancer_download": 0,
"balancer_download_speed": -120},
"3", {"balancer_upload": 12,
"balancer_upload_speed": -90,
"balancer_download": 8,
"balancer_download_speed": -20}]";
我如何获得javascript值:
first id ==> 2 and values from balancer_upload, balancer_upload_speed, balancer_download, balancer_download_speed
我尝试使用foreach但是没有工作......
更新问题:
完整的JSON格式:
{"total_users":1,"expired_users":4,"free_test":0,"pay_test":0,"total_devices":6,"online_devices":0,"android_devices":0,"enigma_devices":0,"mag_devices":0,"main_upload":0.07,"main_upload_speed":-120,"main_download":3.16,"main_download_speed":-120,"balancer":"[\"2\", {\"balancer_upload\": 0, \"balancer_upload_speed\": -120, \"balancer_download\": 0, \"balancer_download_speed\": -120},\"3\", {\"balancer_upload\": 0, \"balancer_upload_speed\": -120, \"balancer_download\": 0, \"balancer_download_speed\": -120},\"4\", {\"balancer_upload\": 0, \"balancer_upload_speed\": -120, \"balancer_download\": 0, \"balancer_download_speed\": -120},\"5\", {\"balancer_upload\": 0, \"balancer_upload_speed\": -120, \"balancer_download\": 0, \"balancer_download_speed\": -120}]"}
答案 0 :(得分:1)
那个对象不是一个二维数组?它是一个混合型数组。
我建议在使用之前清理数据。
var balancer = [
"2", {"balancer_upload": 0,
"balancer_upload_speed": -120,
"balancer_download": 0,
"balancer_download_speed": -120},
"3", {"balancer_upload": 12,
"balancer_upload_speed": -90,
"balancer_download": 8,
"balancer_download_speed": -20} ] ;
for( var t = 0; t < balancer.length; t+=2 ) {
var id = balancer[t];
var values = balancer[t+1];
// do stuff.
}
编辑
你的balancer是你需要像前面提到的那样解析json的字符串。
var myObj = {
"total_users": 1,
"expired_users": 4,
"free_test": 0,
"pay_test": 0,
"total_devices": 6,
"online_devices": 0,
"android_devices": 0,
"enigma_devices": 0,
"mag_devices": 0,
"main_upload": 0.07,
"main_upload_speed": -120,
"main_download": 3.16,
"main_download_speed": -120,
"balancer": "[\"2\", {\"balancer_upload\": 0, \"balancer_upload_speed\": -120, \"balancer_download\": 0, \"balancer_download_speed\": -120},\"3\", {\"balancer_upload\": 0, \"balancer_upload_speed\": -120, \"balancer_download\": 0, \"balancer_download_speed\": -120},\"4\", {\"balancer_upload\": 0, \"balancer_upload_speed\": -120, \"balancer_download\": 0, \"balancer_download_speed\": -120},\"5\", {\"balancer_upload\": 0, \"balancer_upload_speed\": -120, \"balancer_download\": 0, \"balancer_download_speed\": -120}]"
}
var balancer = JSON.parse(myObj.balancer);