简体   繁体   中英

How to have a single backslash in JSON response using jsonify and flask?

I need a JSON HTTP response to be as follows:

{date: "\\/Date(1411084800000)\\/"}

I have a python dict event with a property date such that

event['date'] = "\\/Date(1411084800000)\\/"

Now when I return the dict using flask I am passing it through jsonify . It is unfortunately escaping the single backslash and adding a double backslash to the JSON. \\\\/Date("1411084800000")\\\\/ . I need to get rid of the double back slash, how should I do this?

You are wondering why I would ever want to return a crazy result like this? Well that is how Kendo Scheduler expects date objects. See http://demos.telerik.com/kendo-ui/scheduler/index

Any help would be appreciated. Thanks!

You are seeing an escaped forward slash . The JSON standard allows any character to be escaped, and the forward slash can be escaped by preceding it with a backward slash. See the Strings section of RFC 7159 .

So \\/ is an just an escaped representation for the value / :

>>> import json
>>> print json.loads(r'{"date": "\/Date(1411084800000)\/"}')
{u'date': u'/Date(1411084800000)/'}

Note how the \\/ is decoded to / in the output. This escaping is entirely optional .

Your browser does the same thing; when any compliant JSON value which includes strings containing \\/ sequences is being parsed, the resulting string values containg just / forward slashes. When the Kendo JSONP response (which does use \\/ in strings) is received, the browser produces the exact same result as a JSONP response with the forward slashes left un-escaped.

Just provide the value in Python with the forward slashes. json.dumps() will not escape the forward slash (it doesn't have to escape it), and your browser and any other JSON compliant parser will produce the exact same value:

>>> print json.dumps({'date': '/Date(1411084800000)/'})
{"date": "/Date(1411084800000)/"}

While Martijn is absolutely correct, he does include a caveat about the far end being compliant. If it isn't, like JustGiving, then you might find the following a useful starting point:

class DateJSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime.date):
            javascript_date = int(o.strftime("%s"))*1000
            return r'\/Date({0}+0000)\/'.format(javascript_date)
        return JSONEncoder.default(self, o)

    def encode(self, o):
        encoded = super(DateJSONEncoder, self).encode(o)
        encoded = encoded.replace(r"\\/", r"\/").replace(r")\\/", r")\/")
        return encoded

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM