0

I am trying to evaluate some json that my ajax request is returning, using the following:

     new Ajax.Request("GetExpenses",
        {method: 'get',
            parameters: {'period': 'all'},
            onSuccess: function(transport) {
                var json = transport.responseText.evalJSON();

            }});

What method calls are available on the json object returned by the evalJSON() method? Is it an array of objects? How do I parse it to get the values?

Barmar
  • 741,623
  • 53
  • 500
  • 612
user1154644
  • 4,491
  • 16
  • 59
  • 102
  • *"Is it an array of objects?"* Depends on the data you are getting. *"How do I parse it to get the values?"* I believe `evalJSON()` does the parsing for you. I you are asking for how to *access* the data, just the usual way you access arrays and objects. – Felix Kling Nov 17 '13 at 22:35
  • Ok, so how would I determine if json contains more than 1 json object? I tried .length but that method is undefined. – user1154644 Nov 17 '13 at 22:37
  • There is no such thing as a "json object". `transport.responseText` is a string containing JSON. After it is parsed you are working with arrays and objects, not JSON. If `json.length` is undefined, then `json` might be an object. Use `console.log` to inspect its structure and access it accordingly. – Felix Kling Nov 17 '13 at 22:38
  • 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 17 '13 at 22:39
  • Ok, so what would be a smart way to determine if I'm dealing with a single object, or an array? I would think that there are patterns available to do this? – user1154644 Nov 17 '13 at 22:44
  • If the API is supposed to return a set of objects, then the smartest solution would be if the API *always* returns an array of objects, even if it means that the array only contains one object. That of course works only if you can actually change the service to do that. – Felix Kling Nov 17 '13 at 22:46
  • So with the assumption that it is an object, would I call json.attributeName to get the value of a particular attribute? – user1154644 Nov 17 '13 at 22:52
  • Yep, that's how objects work. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects. What you call "attribute" is called "property" in JS. – Felix Kling Nov 17 '13 at 22:53

0 Answers0