2013-07-25 37 views
0

從地理位置API瀏覽器查詢數組,我得到這個:創建(json-)從瀏覽器查詢字符串

browser=opera&sensor=true&wifi=mac:B0-48-7A-99-BD-86|ss:-72|ssid:Baldur WLAN|age:4033|chan:6&wifi=mac:00-24-FE-A7-BA-94|ss:-83|ssid:wlan23-k!17|age:4033|chan:10&wifi=mac:90-F6-52-3F-60-64|ss:-95|ssid:Baldur WLAN|age:4033|chan:13&device=mcc:262|mnc:7|rt:3&cell=id:15479311|lac:21905|mcc:262|mnc:7|ss:-107|ta:0&location=lat:52.398529|lng:13.107570

我想訪問所有本地結構單一數值。我的方法是更深入地創建一個json數組,然後先將它分爲「&」,然後再將其分解爲「=」,以獲得查詢中所有值的數組。另一種方法是使用正則表達式(\ w +)=(。*)在「&」分割後以相同的深度結束,但我需要更多可以作爲數據類型訪問的細節。

結果數組應該是這樣的:

{ 
    "browser": ["opera"], 
    ... 
    "location": [{ 
        "lat": 52.398529, 
        "lng": 13.107570 
       }], 
    ... 
    "wifi": [{  
       "mac": "00-24-FE-A7-BA-94", 
       "ss": -83, 
       ... 
      }, 
      {  
       "mac": "00-24-FE-A7-BA-94", 
       "ss": -83, 
       ... 
      }] 

或者相似的,我可以用一個額外的JSON庫解析使用Python訪問值的東西。有人能幫忙嗎?

回答

0

這裏從字典

import re 
import json 

transform a string to a dictionary, sepfield is the field separator, 
def str_to_dict(s, sepfield, sepkv, infields=None): 
    """ transform a string to a dictionary 
     s: the string to transform 
     sepfield: the string with the field separator char 
     sepkv: the string with the key value separator 
     infields: a function to be applied to the values 

     if infields is defined a list of elements with common keys returned 
     for each key, otherwise the value is associated to the key as it is""" 

    pattern = "([^%s%s]*?)%s([^%s]*)" % (sepkv, sepfield, sepkv, sepfield) 
    matches = re.findall(pattern, s) 
    if infields is None: 
     return dict(matches) 
    else: 
     r=dict() 
     for k,v in matches: 
      parsedval=infields(v) 
      if k not in r: 
       r[k] = [] 
      r[k].append(parsedval) 
     return r 

def second_level_parsing(x): 
    return x if x.find("|")==-1 else str_to_dict(x, "|",":") 

json.dumps(str_to_dict(s, "&", "=", second_level_parsing)) 

您可以輕鬆地擴展爲多層次傳遞解決方案。請注意,內場函數是否定義的行爲與您要求的輸出相匹配。

+0

非常感謝你,太棒了! – tofix