Reputation: 5332
I can't seem to access my objects.
after parsing the server string:
var json = JSON.parse(myJsonText):
I get the below with an alert:
alert(json.param1)
{"ID":17,"Name":"swimming pools","ParentID":4,"Path":""},
{"ID":64,"Name":"driveways","ParentID":4,"Path":""}
Now, I am trying to access ID and Name.
I have tried:
json.param1[0].ID
json.param1[0]["ID"]
json.param1[0][0]
And a lot of others that really don't make much sense such as:
json[0].ID or
json.param1.ID etc...
I am getting (for example, in the case of json.param1[0].ID):
param1.0.ID is null or not an object.
Any ideas?
Upvotes: 0
Views: 1185
Reputation: 38550
Try this
// you already have this bit
var json = JSON.parse(myJsonText);
alert(json.param1);
// add this
var tmp_param1 = JSON.parse(json.param1);
json.param1 = tmp_param1;
alert(json.param1); // should print [object, object] or similar
alert(json.param1[0].ID); // should print "17"
alert(json.param1[0].Name); // should print "swimming pools"
Upvotes: 2
Reputation: 123513
To compile and expand on all of the comments... ;)
Your first clue that something's wrong is your alert:
alert(json.param1)
Instead of getting:
{"ID":17,"Name":"swimming pools","ParentID":4,"Path":""},
{"ID":64,"Name":"driveways","ParentID":4,"Path":""}
You should be getting something similar to the following:
[object],[object]
Try alerting the typeof
array element, itself:
alert(typeof json.param1[0]) //=> should say "object"
If you get anything besides "object"
, either the JSON isn't formatted correctly or the parser is failing.
One good clue as to which is wrong is if the original JSON looks like this:
{"param1" : [
"{\"ID\":17,\"Name\":\"swimming pools\",\"ParentID\":4,\"Path\":\"\"}",
"{\"ID\":64,\"Name\":\"driveways\",\"ParentID\":4,\"Path\":\"\"}"
]}
Then, it's probably the JSON that's broken. (Sorry ;)
On the other hand, if your JSON looks like this:
{"param1" : [
{"ID":17,"Name":"swimming pools","ParentID":4,"Path":""},
{"ID":64,"Name":"driveways","ParentID":4,"Path":""}
]}
Then, it's probably the parser.
Upvotes: 1
Reputation: 546263
if json.param1
is what you said it is, then json.param1[0].ID
should work (and evaluate to "17").
If it's not working, could you show us the text you're parsing to generate the JSON object?
Upvotes: 0
Reputation: 3102
If you are receiving the raw JSON in the alert, then that would lead me to believe there is a problem w/ the JSON you are trying to parse.
Upvotes: 2
Reputation: 78282
That looks like invalid JSON. Try wrapping it in the brackets which makes it a valid array of JSON objects. Then access it by index.
[
{"ID":17,"Name":"swimming pools","ParentID":4,"Path":""},
{"ID":64,"Name":"driveways","ParentID":4,"Path":""}
]
Upvotes: 2