[Django]-JSON string parsing error in Python

3đź‘Ť

Use a regular expression to match the offending value and use re.sub to escape the match.

import re
import json

data = '{"Reply":{"Header":{"Method":"mGSSCBetHistory","ErrorCode": "0","MerchantID":"BETSTARtest","MessageID": "H140201152657m6k3f"},"Param":{"TotalRecord":"1","BetDatas":"[{"Column1":""}]","ErrorDesc": ""}}}'

def escape(match_obj):
    print(match_obj.group(1))
    return match_obj.group(1).replace('"','\"')
REGEX = '(?<="BetDatas":")(\S+)(?=",)'

data = re.sub(REGEX, escape, data)
print(data)
👤Crispin

2đź‘Ť

If you exclude “BetDatas” as you correctly guessed then it parses properly

import json
json.loads('{"Reply":{"Header":{"Method":"mGSSCBetHistory","ErrorCode": "0","MerchantID":"BETSTARtest","MessageID": "H140201152657m6k3f"},"Param":{"TotalRecord":"1","ErrorDesc": ""}}}')

{u’Reply’: {u’Header’: {u’ErrorCode’: u’0′, u’MessageID’: u’H140201152657m6k3f’, u’Method’: u’mGSSCBetHistory’, u’MerchantID’: u’BETSTARtest’}, u’Param’: {u’ErrorDesc’: u”, u’TotalRecord’: u’1′}}}

There is no obvious way to handle this, it depends on the API provider rectifying their JSONs.

👤Meghdeep Ray

Leave a comment