Praful Bagai
Praful Bagai

Reputation: 17372

jQuery - Cannot parse json

I'm sending a response through my Python server in json, using json.dumps

return '{"status":200, "response":%s}' % (json.dumps(data))

I'm retrieving it via jQuery, in the following fashion.

$.ajax({
        dataType: "jsonp",
        type : "GET",
        url: url,
        data : {},
        success : function(result){
            alert(result)
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR)
            alert(textStatus)
            alert(errorThrown)
        },
    });

The response that I get is

{
    "status": 200,
    "response": {
        "count": 2,
        "2015_03_16": [
            {
                "imei1": "111",
                "status": "Success",
                "imei2": "NA",
                "msisdn": "111",
                "offer_id": "1",
                "ctype": "pre",
                "date": "2015-03-16 06:42:46",
                "recharge_api": "12",
                "points": "2",
                "operator": "vodafone",
                "model": "MicromaxA069",
                "circle": "delhi"
            },
            {
                "imei1": "111",
                "status": "Success",
                "imei2": "NA",
                "msisdn": "111",
                "offer_id": "1",
                "ctype": "pre",
                "date": "2015-03-16 06:42:46",
                "recharge_api": "12",
                "points": "2",
                "operator": "vodafone",
                "model": "MicromaxA069",
                "circle": "delhi"
            }
        ]
    }
}

upon alerting the error, it shows parserror. I've read various post that the data needed to be send in json for jquery to parse it, and I've done the same. Why I'm still getting the error?

EDIT

I just created a dummy code,

<html>
    <body>
        Helo
    </body>
    <script type="text/javascript" src="untitled.js"></script>
    <script type="text/javascript">
    $(function(){
        $.ajax({
            type : "GET",
            url: 'a.json',
            data : {},
            success : function(result){
                alert(result)
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(jqXHR)
            },
        });
    });

    </script>
</html>

I created a file a.json in the same directory, having the following content.

{
    "status": 200,
    "response": {
        "count": 3,
        "2015_03_16": [
            {
                "InstallCount": "1",
                "ad": "Amazon",
                "conversion": null,
                "ClickCount": "0"
            },
            {
                "InstallCount": "2",
                "ad": "Mobikwik",
                "conversion": "0.6667",
                "ClickCount": "3"
            },
            {
                "InstallCount": "1",
                "ad": "Quickr",
                "conversion": "1.0000",
                "ClickCount": "1"
            }
        ]
    }
}

When I ran the above HTML code, it still goes into the error function and logs the following result.

readyState 4
responseText "{"status":200, "response":{"count": 3, "2015_03_16": [{"InstallCount": "1", "ad": "Amazon", "conversion": null, "ClickCount": "0"}, {"InstallCount": "2", "ad": "Mobikwik", "conversion": "0.6667", "ClickCount": "3"}, {"InstallCount": "1", "ad": "Quickr", "conversion": "1.0000", "ClickCount": "1"}]}} "
status 200
statusText "OK"
abort function(a)
always function()
complete function()
done function()
error function()
fail function()
getAllResponseHeaders function()
getResponseHeader function(a)
overrideMimeType function(a)
pipe function()
progress function()
promise function(a)
setRequestHeader function(a, b)
state function()
statusCode function(a)
success function()
then function()

Now what wrong am I doing You can try the above code in your system as well.

Upvotes: 2

Views: 581

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121484

You are telling jQuery to expect JSONP, not JSON. JSONP is JSON wrapped in a callback, but you provided no such callback wrapper.

Remove the p from the jsonp type in the $.ajax() call, or add a callback wrapper. The callback name is found in the callback GET parameter.

You'll also need to return a proper JSON response with the right content type. Since you are using Flask the easiest way to do this is to use the jsonify() function; it'll create a response object with the correct content type set for you:

from flask import jsonify

# ...

return jsonify(status=200, response=data)

The alternative would be to return the string you built but with a status code and header dictionary:

return '{"status":200, "response":%s}' % (json.dumps(data)), 200, {'Content-Type': 'application/json'}

Either way, you can then use the decorator from this Flask snippet to also support JSONP. You'd put it after the @app.route() decorator, before your view function:

@app.route('/some/path')
@jsonp
def your_view_function():
    # ...

Upvotes: 4

linchao
linchao

Reputation: 1

server return error

you can find error with Chrome Developer Tools

open Developer Tools, click "Console"

res = [{"status":200, "response":{"count": 2, "2015_03_16": [{"imei1": "111", "status": "Success", "imei2": "NA", "msisdn": "111", "offer_id": "1", "ctype": "pre", "date": "2015-03-16 06:42:46", "recharge_api": "12", "points": "2", "operator": "vodafone", "model": "MicromaxA069", "circle": "delhi"}, {"imei1": "111", "status": "Success", "imei2": "NA", "msisdn": "111", "offer_id": "1", "ctype": "pre", "date": "2015-03-16 06:42:46", "recharge_api": "12", "points": "2", "operator": "vodafone", "model": "MicromaxA069", "circle": "delhi"}]}}

you will get error info : Uncaught SyntaxError: Unexpected token }

easy to find end of response need a "]"

and sorry for my poor english

Upvotes: 0

Related Questions