Search code examples
pythonajaxjsonpyramid

can't access json object from python method


I've looked at many answers showing how to access a json in a python method however I can't seem to get mine to work.

Here is my ajax call

var data = {
        'customer': customer,
        'custID': custID,
        'date': date,
        'jobNum': jobNum,
        'deviceID': deviceID
    }

//create customer
if (custID === undefined) {
    $.ajax({
        url: "http://127.0.0.1:6543/test",
        type: "POST",
        data: JSON.stringify(data),
        dataType: 'json',
        success: function(response, textStatus, jqXHR) {
            alert(response);
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(textStatus, errorThrown);
        }
    });
}
else {
    //empty
}

and here is my python method:

@view_config(route_name="test", renderer='templates/main.html')
def new_sheet(request):
    response = request.POST
    myObject = json.loads(response)

    #print myObject["customer"]

    test = "hello"
    return dict(test=test)

somewhat new to python so pardon my limited understanding. How can I get my json and access the object properties? all i get in my cmd when i tried print was ValueError: No JSON object could be decoded


Solution

  • pyramid has native JSON request support. Set the contentType parameter to application/json to tell the server that you are sending JSON, preferably with a character set (UTF8):

    $.ajax({
        url: "http://127.0.0.1:6543/test",
        type: "POST",
        data: JSON.stringify(data),
        contentType: 'application/json; charset=utf-8'
        dataType: 'json',
        success: function(response, textStatus, jqXHR) {
            alert(response);
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(textStatus, errorThrown);
        }
    });
    

    and on the server side use request.json_body:

    @view_config(route_name="test", renderer='templates/main.html')
    def new_sheet(request):
        myObject = request.json_body
    
        print myObject["customer"]
    
        test = "hello"
        return dict(test=test)