Jump to content

Recommended Posts

  • Модератор

Имеем:

var json = '{"status":"OK","status_code":100,"sms":{"1111111111111111":{"status":"ERROR","status_code":203,"status_text":"Нет текста сообщения"}},"balance":1485.17}';
j = JSON.parse(json);
alert( j.status ); // прочитаем status = OK
alert( j.status_code ); // прочитаем status_code = 100
alert( j.balance); // прочитаем balance = 1485.17

Как прочитать выделенное синим? 

Структурно json  выглядит так:

{
"status":"OK",
"status_code":100,
"sms":{
   "1111111111111111":{
   "status":"ERROR",
   "status_code":203,
   "status_text":"Нет текста сообщения"
    }
  },
"balance":1485.17
}

 

Link to post
Share on other sites
  • Administrators
json = {
"status":"OK",
"status_code":100,
"sms":{
   "1111111111111111":{
   "status":"ERROR",
   "status_code":203,
   "status_text":"Нет текста сообщения"
    }
  },
"balance":1485.17
};
console.log(json.status);
console.log(json.status_code);
console.log(json.sms);
console.log(json.balance);
console.log(json.sms[1111111111111111].status);

 

Link to post
Share on other sites
  • Модератор

Тут фишка в том, что 1111111111111111111 - это объект, его имя неизвестно, их может быть больше.

Вот пример для иллюстрации:

{
    "status": "OK", 
    "status_code": 100, 
    "sms": {
        "1111111111111111": {
            "status": "OK", 
            "status_code": 100, 
            "sms_id": "000000-10000000"
        },
        "2222222222222222": {
            "status": "ERROR",
            "status_code": 207,
            "status_text": "На этот номер (или один из номеров) нельзя"         }
    } ,
    "balance": 1485.16 
}

 

Link to post
Share on other sites
  • Administrators
json = {
    "status": "OK", 
    "status_code": 100, 
    "sms": {
        "1111111111111111": {
            "status": "OK", 
            "status_code": 100, 
            "sms_id": "000000-10000000"
        },
        "2222222222222222": {
            "status": "ERROR",
            "status_code": 207,
            "status_text": "На этот номер (или один из номеров) нельзя"         }
    } ,
    "balance": 1485.16 
};
for (var key in json.sms) {
  console.log(key, json.sms[key]);
}

 

Link to post
Share on other sites
  • Модератор

Devilstar, спасибо, с циклом понятно. Как прочитать внутри:status и status_code найденного объекта ?

Вроде как:

for (var key in j.sms) {
alert(key, j.sms[key]); 
alert(j.sms[key].status);
alert(j.sms[key].status_code);
alert(j.sms[key].status_text);
}

Link to post
Share on other sites
  • files locked this topic
Guest
This topic is now closed to further replies.
  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...