Parsing json with jquery Wrapping one's head around the json/ajax/jquery relationship is quite a battle for someone new to it. But what a fun puzzle! One of the most confusing parts has been how to frame this question. 

Using php in my module file, utilizing db_query function, the database query has been made, and now we're going to loop through the results, create json data and encode it and send it back to jquery for re-inclusion into our website.

$json = array();
        foreach ($query as $row) {

      $fid = $row-&gt;thefid;
      $file = file_load($fid);


      $jsonelement=array(

         'title' =&gt; $row-&gt;title,
         'path' =&gt; $file-&gt;uri,
         'style_name' =&gt; 'swatch'

        );
          array_push($json,$jsonelement);   
    } 

        // encode to json
        $jsonstring = drupal_json_encode($json);

        //output the json string
        drupal_json_output($jsonstring);


This returns this json string:

[{"title":"Test Swatch 5","path":"4DS_AB_BrittanyBeige_CAT.jpg","style_name":"swatch"},{"title":"Test Swatch 6","path":"4DS_AB_ArdennesGray_CAT.jpg","style_name":"swatch"}]

Where I am having trouble, is figuring out how to access each element.

A simple side example to illustrate the issue without an array :

var data = jQuery.parseJSON('{"title":"Test Swatch 5","path":"4DS_AB_BrittanyBeige_CAT.jpg","style_name":"swatch"}');

alert (data.title);
data.title returns the string Test Swatch 5, which is what I expect.

However, in the output I have (back at the top of the question) the json object(s) has an extra set of brackets around it suggesting another array that I am not sure how to access, but for now I will call it x. 

My question is 2 parts and any one of the solutions will get me to where I need to be.

1) Is there a way to get the key value pairs out of the current output I have already created? Any example would be helpful.

2) Is there a way to frame the output in a way to utilize x as the name of the array so that the values can be accessed via myjson.x.title or myjson.x.path or myjson.x.style_name, etc..?

I noticed a very similar question here with no answer as well
https://stackoverflow.com/questions/1607937/how-to-parse-json-array-in-jquery
You should be able to access the JSON response objects by saying data[0] and data[1]. These will be the swatches. So instead of namespacing the objects (swatches) by name, as in "myjson.x.path" you will be able to access them by index, as in "myjson[#].path". Does it imply any limitation for your setup?

As per getting the key/value pairs, you should be able to use either jQuery.each function, or native js for (item in coll) traversal.