views:

47

answers:

3

how to access JSON array elements for the following JSON Code? further how do i calculate the size of the returned object array?

[
{
lastInvAmt: 0
bwHrs: 0
nbwHrs: 0
unbilledAmt: 0
unbilledHrs: 0
dbID: 0`
},{
lastInvAmt: 0
bwHrs: 0
nbwHrs: 0
unbilledAmt: 0
unbilledHrs: 0
dbID: 0`
}]
A: 

Why can't you assign it to variable? Or I don't understand anything? :)

edited to work with json string

var ar = eval('[
{
lastInvAmt: 0
bwHrs: 0
nbwHrs: 0
unbilledAmt: 0
unbilledHrs: 0
dbID: 0
},{
lastInvAmt: 0
bwHrs: 0
nbwHrs: 0
unbilledAmt: 0
unbilledHrs: 0
dbID: 0
}]');

Why do you have single quote dbID: 0`. Is it spelling error?

Danil
The OP probably gets above thingadongdong as a string in JSON, which he wants to be converted to a real object (or array, in this case).
Marcel Korpel
then it is required to use eval of course. I will edit my code.
Danil
No, it is not required and *could* even be dangerous (malicious code injection). Use a JSON parser instead.
Marcel Korpel
yes that was a spelling error.
BinCode
A: 

That doesn't look like valid json data to me. It should look like this:

var json = { one: {
    lastInvAmt: 1,
    bwHrs: 2,
    nbwHrs: 3,
    unbilledAmt: 4,
    unbilledHrs: 5,
    dbID: 6
},
    two: {
        lastInvAmt: 11,
        bwHrs: 22,
        nbwHrs: 33,
        unbilledAmt: 44,
        unbilledHrs: 55,
        dbID: 66
    }
};

Then you access it like this:

arrJson = eval(json);
alert(arrJson['two']['lastInvAmt']);

etc...

Paul Spangle
Your example contains a JavaScript object in literal notation, but you still use `eval` to do something?
Marcel Korpel
Why would you use a string keyed object for numbering when there is a perfectly good array mechanism in JSON? You've actually made the original problem worse here.
Ollie Edwards
Gosh - you're right. Didn't realise I'd been doing it so wrongly - thanks for the pointers.
Paul Spangle
+1  A: 

Apart from the fact that above thingadongdong isn't a valid JSON string (test this with jsonlint.com), you'll have to parse your returned string with something like JSON.parse or json-sans-eval.

After that, you can access your array like any other array, so you can count the number of elements using the length property.

Assuming your responseText contains a valid JSON string (with all strings encapsulated in double quotes and commas separating key/value pairs), like

[
    {
        "lastInvAmt": 0,
        "bwHrs": 0,
        "nbwHrs": 0,
        "unbilledAmt": 0,
        "unbilledHrs": 0,
        "dbID": 0 
    },
    {
        "lastInvAmt": 0,
        "bwHrs": 0,
        "nbwHrs": 0,
        "unbilledAmt": 0,
        "unbilledHrs": 0,
        "dbID": 0
    }
]

you can do something like

var myArray = JSON.parse(responseString);
var length = myArray.length;
alert(myArray[0].lastInvAmt);  // outputs '0'

See thingadongdong.com.

Marcel Korpel
Thanks! works like a charm
BinCode