0

How can I get access to this JSON Array using jQuery? I've currently processed the array from an API to the console.log() which is displayed in this format

Object {already_liked: false, media_id: "1234567890", likeResult: Object}
    already_liked: false
    likeResult: Object
        data: null
        meta: Object
            code: 200
            __proto__: Object
        __proto__: Object
    media_id: "1234567890"
    __proto__: Object

I am getting this response from an AJAX request which is formatted in such way

$.get('/likemedia', {
    mediaid: $(this).data("id")
}, function(data){
    console.log(data.html);
}, 'json');

The response from /likemedia is formatted in such way

{"html":{"already_liked":false,"media_id":"1234567890","likeResult":{"meta":{"code":200},"data":null}}}

I then tried acessing the JSON array key of "meta['code']" using this format

data.html.likeResult.meta.code

Which was to now avail, how can I get the value of 'data.likeResult.meta.code'?

I attempted to do the following which results in it throwing the array into the console.log

if (data.html.likeResult.meta.code === "200") {
    alert("200 META CODE!");
} else {
    console.log(data.html);
}
Curtis
  • 2,646
  • 6
  • 29
  • 53
  • 1
    Sorry, but the output of your console.log statement you pasted here makes no sense, it' s incomplete. We need to see the object's structure if we are to help you any further – Elias Van Ootegem Nov 24 '13 at 16:44
  • I've gone ahead and added more information as to why this could be a problem – Curtis Nov 24 '13 at 16:46
  • possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Felix Kling Nov 24 '13 at 16:47
  • 1
    @JonathanLonowski: I know that much, but the OP should realize that ` Object}` followed by a ` likeResult: Object` looks as though he's logging a great number of objects... at least 1 thing is obvious: `meta.code` is not a property of `likeResult`, because the `meta` property is shown on the same level as `likeResult`... basic stuff – Elias Van Ootegem Nov 24 '13 at 16:48
  • 1
    @EliasVanOotegem: Looks like the indentation is just off, based on the JSON they posted. That also makes sense considering the `__proto__` entries. – Felix Kling Nov 24 '13 at 16:49
  • @FelixKling: indeed, though JSON string wasn't here at first, and going on the copy-pasted stuff, I was made to believe the `meta` property was on the same level as the `likeResult` property.... my bad – Elias Van Ootegem Nov 24 '13 at 16:51
  • 1
    If `data.html.likeResult.meta.code` doesn't work, the you must get an error at some point. What is the error? [Learn how to **debug** JavaScript](http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820) – Felix Kling Nov 24 '13 at 16:52
  • You are of course trying to access the object inside the callback, and not elsewhere in the script ? – adeneo Nov 24 '13 at 16:54
  • added more information to the question – Curtis Nov 24 '13 at 16:55
  • That's why its always good to post a complete example, *what* you are trying to do and what is happening. If you had said *"I try to compare this value but it always executes the else branch"* instead of *"I tried to access this value but to no avail*", then would have already known a lot more. – Felix Kling Nov 24 '13 at 17:01

2 Answers2

2

You are accessing the data correctly, but you are doing a strict comparisons of a number against a string. That is always false. Strict comparison means that the data type of both values must match as well. So, compare against a number instead:

data.html.likeResult.meta.code === 200

instead.

You can clearly see that code is a number because the value is not in double quotes:

{"code":200}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

You're doing a type-and-value check on a Number type, comparing it to a string. That will always evaluate to false. When you're of the type, type-and-value checks are something I encourage, and greatly improve of, but when dealing with JSON, I wouldn't just assume a type. Instead I'd either write:

if (data.html.likeResult.meta.code == 200)

or go for:

if (+(data.html.likeResult.meta.code) === 200)//explicitly coercing to number

Anyways, I'd also check the object before accessing that many nested properties:

if (data.hasOwnProperty('html'))
{
}

To avoid errors when accessing a non-existant property, which would terminate your entire script.
Perhaps this function can help you with that:

function checkObject(obj, properties)
{
    var i, data = obj;
    for (i=0;i<properties.length;++i)
    {
        if (!data.hasOwnProperty(properties[i]))
        {
            return undefined;
            //or throw {'Property: ' + properties[i] + '  not found' , i}
        }
        data = data[properties[i]];
    }
    return data;
}

This provides a safer approach to JSON objects, IMO. In your case, you could call this function like so:

var meta = checkObject(data, ['html','likeResult','meta','code']);
if (!meta)
{//one of the properties wasn't available, deal with that here
}
//all was well, so now:
if (meta.code == 200)
{//...
}
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • *"when dealing with JSON, I wouldn't just assume a type"* If you are working with a proper API, why not? – Felix Kling Nov 24 '13 at 17:09
  • @FelixKling: a couple of reasons: if you don't control the API, and the service provider decides to use a different lib for JSON formatted data, and that lib just blindly quotes everything, including ints, then strict checking won't help. If you _do_ control the API, chances are it's being developed alongside the JS code that calls it, if someone finds this _meta_ property useful for pumping other, unexpected data, like a date, over to your code, again, a strict comparison would fail. Basically, it's data you don't have full control over, so I'd avoid checking as strict as JS allows you to... – Elias Van Ootegem Nov 24 '13 at 17:13