I am reading information from a JSON string, and when I execute
console.log(record.seenTime.time.seenEpoch)
it display the right information.
But when I use console.log(record.seenTime.time[0].seenEpoch), I get an error saying :
TypeError: Cannot read property 'seenEpoch' of undefined.
Here is an example set of data:
{
seenTimes: {
time: {
seenTime: '2014-09-10T20:18:32Z',
seenEpoch: 1410380312
}
}
}
Anyone know what am I doing wrong? Thanks
record.seenTimes in this case is an Object, not an Array, you can verify that using
typeof record.seenTimes
Because of that, time[0] returns undefined.
seenEpoch is a property of the ONE AND ONLY time object, therefore, you access it using record.seenTimes.time.seenEpoch
For once, I'll recommend reading something from w3schools : JSON Syntax
It'll show you examples of what can be stored in JSON.
EDIT :
Your sample record.seenTimes will not be able to store multiple time objects, as it uses the curly brackets {} which indicate that it's meant to store an object , if you want to be able to store multiple time objects, ie: an Array, your JSON will have to look like :
record {
seenTimes: [
{
time: {
seenTime: '2014-09-10T20:18:32Z',
seenEpoch: 1410380312
}
},
{
time: {
seenTime: '2014-09-10T20:18:32Z',
seenEpoch: 1410380312
}
}
]
}
Note the square brackets that say that seenTime holds an array.
And as slebetman noted :
Also note that in javascript, an object defined as having multiple identical keys are technically invalid. But most implementations take the last definition. For example, the object: {a:1,a:2,a:3} is exactly the same as {a:3}. So if you don't use an array then there is only one time object even if it appears twice in the JSON string.