python - Create (json-) array from browser query string -


from geolocation api browser query, this:

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

i access single values local structured. approach create json array more in depth, split "&" first , "=" afterwards array of values in query. approach use regex (\w+)=(.*) after splitting "&" ends in same depth need there more details accessible datatype.

the resulting array should like:

{     "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,                  ...             }] 

or similar can parse additional json library access values using python. can this?

here solution passing dictionary

import re import json  transform string dictionary, sepfield field separator,  def str_to_dict(s, sepfield, sepkv, infields=none):     """ transform string dictionary        s: string transform        sepfield: string field separator char        sepkv: string key value separator        infields: function applied values         if infields defined list of elements common keys returned        each key, otherwise value associated key is"""      pattern = "([^%s%s]*?)%s([^%s]*)"  % (sepkv, sepfield, sepkv, sepfield)     matches = re.findall(pattern, s)     if infields none:         return dict(matches)     else:         r=dict()         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)) 

you can extend multiple levels. note different behaviour whether infields function defined or not match output asked for.


Comments

Popular posts from this blog

php - get table cell data from and place a copy in another table -

javascript - Mootools wait with Fx.Morph start -

php - Navigate throught databse rows -