oriharel
oriharel

Reputation: 10468

jQuery .getJSON and escape character

I call .getJSON and the response is a JSON string that has a lot of \" characters. The callback simply won't fire when launching the page on chrome.I read that it won't fire because the JSON string is not JSON-validated. (although it passes the JSONLint test).

when launching the page in the built-in web browser of eclipse, the callback does fire, so I can show you the response:

{"merchants": ["{\"loyaltyLevel\": 3, \"distance\": 100.5, \"imageUrl\": \"http://1.bp.blogspot.com/-hY-Kri63wzs/TeHzpxJ2BJI/AAAAAAAAA4Q/pmq2Yvki8WY/s1600/funny-dog-picture-ass.jpg\", \"name\": \"Papa Kapa\", \"credit\": 25000}", "{\"loyaltyLevel\": 3, \"distance\": 100.5, \"imageUrl\": \"http://1.bp.blogspot.com/-hY-Kri63wzs/TeHzpxJ2BJI/AAAAAAAAA4Q/pmq2Yvki8WY/s1600/funny-dog-picture-ass.jpg\", \"name\": \"Papa Kapa\", \"credit\": 25000}", "{\"loyaltyLevel\": 3, \"distance\": 100.5, \"imageUrl\": \"http://1.bp.blogspot.com/-hY-Kri63wzs/TeHzpxJ2BJI/AAAAAAAAA4Q/pmq2Yvki8WY/s1600/funny-dog-picture-ass.jpg\", \"name\": \"Papa Kapa\", \"credit\": 25000}", "{\"loyaltyLevel\": 3, \"distance\": 100.5, \"imageUrl\": \"http://1.bp.blogspot.com/-hY-Kri63wzs/TeHzpxJ2BJI/AAAAAAAAA4Q/pmq2Yvki8WY/s1600/funny-dog-picture-ass.jpg\", \"name\": \"Papa Kapa\", \"credit\": 25000}", "{\"loyaltyLevel\": 3, \"distance\": 100.5, \"imageUrl\": \"http://1.bp.blogspot.com/-hY-Kri63wzs/TeHzpxJ2BJI/AAAAAAAAA4Q/pmq2Yvki8WY/s1600/funny-dog-picture-ass.jpg\", \"name\": \"Papa Kapa\", \"credit\": 25000}"]}

I did some debugging there and indeed Javascript won't jsonParse this.

any ideas?

here is my code:

    <!DOCTYPE html>
<html>
<head>
  <style>img{ height: 100px; float: left; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div id="images">

</div>
<script>
$.getJSON("some_url",
  function(data) 
  {
    alert("success");
  });
</script>

</body>
</html>

Here is the server side code:

import logging
log = logging.getLogger(__name__)
import appcardrestapi.Errors
import sys
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPUnauthorized, HTTPBadRequest
from appcardrestapi.BL.usermanagement import UserObj

class merchant():

    def __init__(self,name,imageUrl,loyaltyLevel,distance,credit):
        self.name = name
        self.imageUrl = imageUrl
        self.loyaltyLevel = loyaltyLevel
        self.distance = distance
        self.credit = credit

    def getJson(self):
        import json
        return json.dumps({'name':self.name, 'imageUrl':self.imageUrl,'loyaltyLevel':self.loyaltyLevel,'distance':self.distance,'credit':self.credit})


@view_config(route_name='GetMyMerchantsList', renderer='json')
def GetMyMerchantsList(request):

    rc = True
    #
    # Make sure got here with proprt JSON body, if not log and go home
    #
    try:
        log.debug('+ %s()', sys._getframe().f_code.co_name)
        #jsonBody = json.loads(request.GET)

        # Check authentication token
        authenticationToken = request.GET.getone('authenticationToken')
        token = authenticationToken.encode('ascii', 'ignore')

        user = UserObj.User(authenticationToken=token)

        rc, errorMsg = user.ValidateTokenAndLoadUser(request)
        import json


        if True == rc:
            location = request.GET.getone('location').encode('ascii', 'ignore')
            i = 0
            merchants = []
            while i < 5 :

                m = merchant('Papa Kapa','http://1.bp.blogspot.com/-hY-Kri63wzs/TeHzpxJ2BJI/AAAAAAAAA4Q/pmq2Yvki8WY/s1600/funny-dog-picture-ass.jpg',3,100.5,25000)
                print m.getJson()
                merchants.append(m.getJson())
                i = i + 1


            response = json.dumps({'merchants':merchants})
            return response

    except Exception as e:
        print e
        errorMsg = appcardrestapi.Errors.InvalideJsonPassed
        log.error('  %s(%s)' % (sys._getframe().f_code.co_name, errorMsg))
        rc = False
        import json
        response = json.dumps({'Error':errorMsg})
        return response

Upvotes: 0

Views: 1756

Answers (2)

Royi Namir
Royi Namir

Reputation: 148554

I saw you json lint reponse

"{\"loyalty

why do you have the first " ?

according to the line

"{\"loyaltyLevel\": 3, \"distance\": 100.5

youll emit ->

"{"loyaltyLevel": 3, "distance": 100.5

so Im asking why is the first " ?

edit :

I understand why you put " in the beginning

you treat it as a string .... which is bad

something linke this :

 "{"loyaltyLevel": 3,....}",

you should remove the surrounding "

and treat it as an object.

Upvotes: 1

Umesh Patil
Umesh Patil

Reputation: 10685

It is the actual JSON given below. It is being parsed properly and all variables are also accessible.

{
    "merchants": [
        {
            "loyaltyLevel": 3,
            "distance": 100.5,
            "imageUrl": "http://1.bp.blogspot.com/-hY-Kri63wzs/TeHzpxJ2BJI/AAAAAAAAA4Q/pmq2Yvki8WY/s1600/funny-dog-picture-ass.jpg",
            "name": "Papa Kapa",
            "credit": 25000
        },
        {
            "loyaltyLevel": 3,
            "distance": 100.5,
            "imageUrl": "http://1.bp.blogspot.com/-hY-Kri63wzs/TeHzpxJ2BJI/AAAAAAAAA4Q/pmq2Yvki8WY/s1600/funny-dog-picture-ass.jpg",
            "name": "Papa Kapa",
            "credit": 25000
        },
        {
            "loyaltyLevel": 3,
            "distance": 100.5,
            "imageUrl": "http://1.bp.blogspot.com/-hY-Kri63wzs/TeHzpxJ2BJI/AAAAAAAAA4Q/pmq2Yvki8WY/s1600/funny-dog-picture-ass.jpg",
            "name": "Papa Kapa",
            "credit": 25000
        },
        {
            "loyaltyLevel": 3,
            "distance": 100.5,
            "imageUrl": "http://1.bp.blogspot.com/-hY-Kri63wzs/TeHzpxJ2BJI/AAAAAAAAA4Q/pmq2Yvki8WY/s1600/funny-dog-picture-ass.jpg",
            "name": "Papa Kapa",
            "credit": 25000
        },
        {
            "loyaltyLevel": 3,
            "distance": 100.5,
            "imageUrl": "http://1.bp.blogspot.com/-hY-Kri63wzs/TeHzpxJ2BJI/AAAAAAAAA4Q/pmq2Yvki8WY/s1600/funny-dog-picture-ass.jpg",
            "name": "Papa Kapa",
            "credit": 25000
        }
    ]
}

Use JSONLintto validate it. If it is returned from the url, it should be visible properly.

Upvotes: 0

Related Questions