How to convert raw javascript object to python dictionary?

前端 未结 4 1690
抹茶落季
抹茶落季 2020-11-29 11:13

When screen-scraping some website, I extract data from

4条回答
  •  心在旅途
    2020-11-29 11:44

    This will likely not work everywhere, but as a start, here's a simple regex that should convert the keys into quoted strings so you can pass into json.loads. Or is this what you're already doing?

    In[70] : quote_keys_regex = r'([\{\s,])(\w+)(:)'
    
    In[71] : re.sub(quote_keys_regex, r'\1"\2"\3', js_obj)
    Out[71]: '{"x":1, "y":2, "z":3}'
    
    In[72] : js_obj_2 = '{x:1, y:2, z:{k:3,j:2}}'
    
    Int[73]: re.sub(quote_keys_regex, r'\1"\2"\3', js_obj_2)
    Out[73]: '{"x":1, "y":2, "z":{"k":3,"j":2}}'
    

提交回复
热议问题