How can I send a JSON object from a Python script to jQuery?

Parker picture Parker · Nov 30, 2010 · Viewed 15.1k times · Source

I've looked through APIs and all sorts of resources, but I can't seem to get the hang of fetching a JSON object from a Python script using AJAX. I'm sure the issue is with how I'm dealing with the JSON object.

First, in a python script on my server, I generate and print a JSON array

import json
print "Content-type: application/json"
print 
print json.dumps(['Price',{'Cost':'99'}])

Then, in a separate html file, I try something like

<body>
<div id="test">
</div>

<script>
 $(document).ready(function() {
  $.getJSON("http://www.example.com/cgi-bin/makeJSON.py", function(data) {
        $('#test').html("JSON Data: " + data.Price);
    });
});
</script>
</body>

But I don't get anything. I'm sure that data.Price is wrong, but I'm also pretty certain that I should be doing something instead of just printing the results of json.dumps

Any help is appreciated! Thanks in advance, and sorry if this is an obvious question.

Answer

Philar picture Philar · Nov 30, 2010

In your case you have enclosed the JSON response in an array. To access price you need to access data[0]. You need to structure your JSON data properly.

The following changes in your Python script should allow you to access data.Price. Let me know in case you still face any issues.

   import json
   print "Content-type: application/json"
   print 
   response={'Price':54,'Cost':'99'}
   print(json.JSONEncoder().encode(response))