0

I have the following json object and I would like to read it (access some data from it)

how can I do it in Javascript please ?

var allSites = 
  {"oldSites":
        [ 
            {
                "site0" : "http://site0.com/", 
                "site1" : "http://site1.com/",
                "site2" : "http://site2.com/" 
            }
        ],
    "newSites":
        [
            {
                "site0" : "http://site0/new", 
                "site1" : "http://site1/new", 
                "site2" : "http://site2/new"
            }
        ]
  };

This is what I did but I get undefined.

var allSites = eval(allSites);
alert(allSites.oldSites.site0);

Thanks.

2
  • 1
    It is not a JSON object, since JSON is only a formatting convention to represent JAVASCRIPT LITERAL OBJECTS under the form of a STRING. Do that without evaling the object(and anyway with a JSON string you should use JSON.parse) Commented Oct 6, 2013 at 10:11
  • 1
    try this : alert(allSites.oldSites[0].site0); Commented Oct 6, 2013 at 10:12

3 Answers 3

3

If your object is defined like you have described, it is not JSON, you do not need to use eval.

Then, since oldSites is an array, you have to index it, like oldSites[0] to get the first value.

Then, get the site0 key of the object retrieved.

So you should use: allSites.oldSites[0].site0

Sign up to request clarification or add additional context in comments.

Comments

2

Use

allSites.oldSites[0].site0

allSites.oldSites is an array. So you have to iterate using index

Comments

1

Please remove the square brackets which make oldSites an array

var allSites = 
  {"oldSites":

            {
                "site0" : "http://site0.com/", 
                "site1" : "http://site1.com/",
                "site2" : "http://site2.com/" 
            }
        ,
    "newSites":

            {
                "site0" : "http://site0/new", 
                "site1" : "http://site1/new", 
                "site2" : "http://site2/new"
            }

  };

2 Comments

I used this solution working good however I need for some reason (a coding reason) to access the site0 index like this : allSites.oldSites[0] instead of allSites.oldSites.site0 is it possible?
your eval statment had 'allSites.oldSites.site0' so removing the [ ] was the option, but yes it depends on requirements :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.