循环JSON对象JavaScript

时间:2016-03-08 20:21:51

标签: javascript arrays json parsing

此JSON对象存在问题....

{
    "1457458375537": {
        "message": "this is the message",
        "subject": "my subject"
    },
    "1457467436271": {
        "message": "test message",
        "subject": "hello"
    }
}

基本上对于每个对象都是长数(例如1457458375537),我想循环但不知道如何引用那个长数并循环遍历完整的JSON对象。

2 个答案:

答案 0 :(得分:2)

// data is all the json you gave in the example
for(var key in data){
    // keys are the numbers 
    // and inner are the objects with message and subject
    var inner = data[key]; 
}

答案 1 :(得分:1)

长号是你json的关键。您可以使用Object.keys()函数循环键:

var data = {
    '1457458375537': {
        'message': 'this is the message',
        'subject': 'my subject'
    },
    '1457467436271': {
        'message': 'test message',
        'subject': 'hello'
    }
};

Object.keys(data).forEach(function(key) {
    console.log(key); // prints property name - long number
    console.log(data[key].message);
    console.log(data[key].subject);
});