How to decode an invalid json string in python

后端 未结 4 1400
自闭症患者
自闭症患者 2020-12-18 03:57

I wonder if there is a way to decode a JSON-like string.

I got string:

\'{ hotel: { id: \"123\", name: \"hotel_name\"} }\'

It\'s no

相关标签:
4条回答
  • 2020-12-18 04:41

    You could try and use a wrapper for a JavaScript engine, like pyv8.

    import PyV8
    ctx = PyV8.JSContext()
    ctx.enter()
    # Note that we need to insert an assignment here ('a ='), or syntax error.
    js = 'a = ' + '{ hotel: { id: "123", name: "hotel_name"} }'
    a = ctx.eval(js)
    a.hotel.id
    >> '123' # Prints
    
    0 讨论(0)
  • 2020-12-18 04:48

    Not very elegant and not robust (and easy to break), but it may be possible to kludge it with something like:

    kludged = re.sub('(?i)([a-z_].*?):', r'"\1":', string)
    # { "hotel": { "id": "123", "name": "hotel_name"} }
    

    You may find that using pyparsing and the parsePythonValue.py example could do what you want as well... (or modified fairly easily to do so) or the jsonParser.py could be modified to not require quoted key values.

    0 讨论(0)
  • 2020-12-18 04:50

    Use demjson module, which has ability to decode in non-strict mode.

    In [1]: import demjson
    In [2]: demjson.decode('{ hotel: { id: "123", name: "hotel_name"} }')
    Out[2]: {u'hotel': {u'id': u'123', u'name': u'hotel_name'}}
    
    0 讨论(0)
  • 2020-12-18 05:01

    @vartec has already pointed out demjson, which works well for slightly invalid JSON. For data that's even less JSON compliant I've written barely_json:

    from barely_json import parse
    print(parse('[no, , {complete: yes, where is my value?}]'))
    

    prints

    [False, '', {'complete': True, 'where is my value?': ''}]
    
    0 讨论(0)
提交回复
热议问题