Convert Google results object (pure js) to Python object

后端 未结 3 1056
逝去的感伤
逝去的感伤 2021-01-15 02:45

So I\'m trying to use Google Map suggest API to request place name suggestions. Unfortunately I can\'t find the docs for this bit.

Here is an example URI:

ht

相关标签:
3条回答
  • 2021-01-15 02:58

    Ugh, that's indeed pretty annoying. It's a JavaScript literal but it — pointlessly — isn't JSON.

    In theory you are supposed to be able to import json.decoder.JSONDecoder from the Python stdlib (or simplejson pre-2.6, which is the same) and subclass it, then pass that subclass to json.loads to override decoder behaviour. In reality this isn't really feasible as json.decoder is full of global cross-references that resist subclassing, and the bit you need to change is slap bang in the middle of def JSONObject.

    So it's probably worth looking at other Python JSON libraries. I found this one which, in ‘non-strict’ mode, will parse unquoted object property names:

    >>> import demjson
    >>> demjson.decode('{suggestion:[{query:"London",interpretation: ...')
    {u'suggestion': [{u'query': u'London', u'operation': 2, u'interpretation': ...
    
    0 讨论(0)
  • 2021-01-15 03:02
    import demjson
    demjson.decode(google.js)
    

    I found this when trying to parse Google Finance option "JSON" data, which, as many note, isn't JSON-compliant.

    demjson saved me writing an obnoxious regex string; it just works.

    0 讨论(0)
  • 2021-01-15 03:20

    I would try to poke around in order to get JSON, but failing that there's this little monstrosity which someone will inevitably yell at me about:

    class Iden(object):
      def __getitem__(name, index):
        return index
    
    notjson = '{...}'
    
    data = eval(notjson, {}, Iden())
    
    0 讨论(0)
提交回复
热议问题