Prashant
Prashant

Reputation: 167

Pass JSON object to Python Script

I want to pass a JSON object of the form {key : value} having many elements to python script . I am able to send the JSON object via Ajax as i can see that in success in response variable in Ajax function.

I am using cgi.FieldStorage() to get POST data . I want to traverse the received JSON object elements and store the key and value in variables . Later , i want to use those variables in printing HTML through that Python Script . I don't know how to proceed and iterate .

Upvotes: 1

Views: 7462

Answers (1)

Daniel
Daniel

Reputation: 42778

You don't need a cgi.FieldStorage, just simply read stdin:

import sys
import json

data = json.load(sys.stdin)

on the client side, you also have to convert your data manually into a json-string:

$.ajax({
    url: "/city/cgi-bin/test1.py",
    type: "post",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify({'lat':30.5 , 'lon' : 4.5}),
    success: function(response){
        //window.location="http://mycity.parseapp.com/city/cgi-bin/test1.py"
        console.log(response.message);
        console.log(response.keys);
        console.log(response.data);

    }
});

Upvotes: 1

Related Questions