1

Ok. After about an hour of trying to think of different ways to do this, my noobness is prevailing (and this question will prove it).

I have a JSON object that looks like so:

{
    newEvent: {
        Event: {
            name: "Something",
            timestamp: {
                month: "07",
                day: "27",
                year: "2013",
                hour: "07",
                min: "42",
                meridian: "pm"
            },
            duration: "2",
            durationMeasure: "min"
        }
    },
    msg: "Event Added"
}

It gets returned in a jquery ajax complete callback function thingy, so its sitting inside a param called data.
Using Chrome, I can console.log() data,data.newEvent,data.msg,data['newEvent'],and data['msg']. The only one that returns anything other than undefined, is data (which prints what's above)

My question: How in the WORLD do I get to anything in data?! Any insight for a JavaScript noob would be greatly appreciated! =)

EDIT: A code snippet:

function eventAdditionalFinish(data,textStatus) {
    console.log("data: ",data,"\n");
    console.log("data['newEvent']: ",data['newEvent'],"\n");
    console.log("data['msg']: ",data['msg'],"\n");

    console.log("data.newEvent: ",data.newEvent,"\n");
    console.log("data.msg: ",data.msg,"\n");
}

Output from Chrome's console:

data:  {"newEvent":{"Event":{"name":"Something","timestamp":{"month":"07","day":"27","year":"2013","hour":"07","min":"42","meridian":"pm"},"duration":"2","durationMeasure":"min"}},"msg":"Event Added"}
data['newEvent']:  undefined 
data['msg']:  undefined 
data.newEvent:  undefined 
data.msg:  undefined 
11
  • works fine when referenced by name thusly: jsfiddle.net/uCPFP... what's the rest of your code look like? (tested in Firefox and Chromium, at least) Commented Jul 28, 2013 at 0:03
  • That's no JSON, it's just a JS object, but your code should work... Commented Jul 28, 2013 at 0:04
  • @mohkhan actually thats a C&P fail. There were a few things after durationMeasure I excluded from this object. Thanks though. =) Commented Jul 28, 2013 at 0:06
  • @PeteScott I added the actual function. Commented Jul 28, 2013 at 0:08
  • 1
    How are you parsing the returned data? jQuery's intellisense, or are you declaring dataType:json Commented Jul 28, 2013 at 0:11

3 Answers 3

1

Ok,

if you use jQuery's json() function in place of ajax(), it will parse the response into a json object.

If, however, you're using the stock functions and getting the result as a string called data then you need something like this to convert it into an object...

response = JSON.parse(data);

you can then do...

response.newEvent.blah;

as you'd expect.

Note that your example isn't actually valid json. Property names should be quoted...

{
    "newEvent": {
        "Event": {
            "name": "Something",
            "timestamp": {
                "month": "07",
                ...

As someone else has pointed out, you could also tell ajax() to convert the result to an object for you (exactly as if you'd called json()) by specifying the data type...

$.ajax({
     ...
     dataType: 'json',
     success: function(data) {
         alert(data.newEvent.Event.name);   
     }
});
Sign up to request clarification or add additional context in comments.

2 Comments

My pleasure. Do check out json.org for the definitive json syntax. Javascript (and many other languages) often support a more lax interpretation of the standard but you might run into problems when you use a new library/language and realise it doesn't support the syntax you're using
I will definitely read that a little bit later! No idea that site existed.
1

I guess it's because you receive a string back from the server. So two options:

  • Specify dataType: 'json' in your ajax parameters.
  • Or use JSON.parse(data) before trying to access the elements

1 Comment

Sorry. JSON.parse(data) is what I needed. But Basic beat you to the answer by 35 secs. =P Thank you though!
0

The following notation should work, just tested it with a similar example

$.ajax({
         url:    'yoururl',
         success: function(data) {
             alert(data.newEvent.Event.name);   
         },
         async:   false
    });

What you will get as the data variable in this case is an object with attributes. To access the attributes write: ObjectsName.attributeName

if there are attributes that are also objects containing attributes, those ones can be accessed like: ObjectsName.attributeName1.attrubteName2 (where attribute1 is also an object containing attributes)

Please correct me if im wrong here, im also new to javascript/jquery-ajax but i had the same problem yesterday:)

Comments

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.