Viren Rajput
Viren Rajput

Reputation: 5766

Escape backslash in JSON encoding python

I m trying to JSON encode the following dict. But in this case, the message which is actually a unicode character DEVANAGARI LETTER.

So, while encoding this dict into a json object, it seems to escaping the backslash("\") with two backslashes("\") in message.

How do I change this to just one backslash "\" after encoding it with json.dumps()

I m using the following custom encoder, to encode the dict to json.

class MyCustomJsonEncoder(json.JSONEncoder):
    def encode(self, obj):
        # the json obj
        count = 0
        for ob in obj:
            obj[count]['message'] = unicode(obj[count]['message']).replace("\\u","\u")
            count += 1
        return super(MyCustomJsonEncoder, self).encode(obj)

[{
    'virality': '4.6%',
    'post_engaged': 150,
    'description': '',
    'post_impressions': 1631,
    'post_story': 75,
    'name': '',
    'source': '',
    'comment_count': 16,
    'link': '',
    'text': '',
    'created_time': '03:10 AM,<br>May 13, 2013',
    'message': '\u092e\u0941\u0930\u0932\u0940 \u0938\u093e\u0930:-     \u0939\u0947 \u092e\u0940\u0920\u0947',
    'id': u'182929845081087_572281819479219',
    'status_type': 'status',
    'likes_count': 55
}]

Upvotes: 0

Views: 5057

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799580

Use a unicode literal so that the \u escape sequence is understood instead of having the compiler think you mean \\u.

u'\u092e....

Upvotes: 1

Related Questions