json - Convert Python String to Dictionary -


i have string:

a = "{user_id:34dd833,category:secondary,items:camera,type:sg_ser}" 

i need convert python dictionary, that:

a = {"user_id":"34dd833", "category": "secondary", "items": "camera", "type": "sg_ser"} 

on top of that, there 2 more issues:

1: "items" key supposed have multiple values, like:

a = {"user_id":34dd833, "category": "secondary", "items": "camera,vcr,dvd", "type": "sg_ser"} 

which apparently comes form of string as:

a = "{user_id:34dd833,category:secondary,items:camera,vcr,dvd,type:sg_ser}" 

so, generalizing based on comma separation becomes useless.

2: order of string can random well. so, string can well:

a = "{category:secondary,type:sg_ser,user_id:34dd833,items:camera,vcr,dvd}" 

which makes process of assuming thins order false one.

what in such situation? many thanks.

if can assume input doesn't quoting or escaping (your example doesn't, doesn't mean it's assumption), , can never have comma-separated multiple keys, multiple values (which is assumption, because otherwise format ambiguous…):

first, let's drop braces, split on colons:

>>> = "{user_id:34dd833,category:secondary,items:camera,vcr,dvd,type:sg_ser}" >>> a[1:-1].split(':') ['user_id', '34dd833,category', 'secondary,items', 'camera,vcr,dvd,type', 'sg_ser'] 

so first entry first key, last entry last value(s), , every entry in between nth value(s) followed comma followed n+1th key. there may other commas there, last 1 splits nth value(s) n+1th key. (and works n=0—there no commas, last comma splits nothing 0th key. doesn't work last entry, unfortunately. i'll later.)

there ways make brief, let's write out explicitly code first, understand how works.

>>> d = {} >>> entries = a[1:-1].split(':') >>> in range(len(entries)-1): ...     key = entries[i].rpartition(',')[-1] ...     value = entries[i+1].rpartition(',')[0] ...     d[key] = value 

this right:

>>> d {'category': 'secondary', 'items': 'camera,vcr,dvd', 'type': '', 'user_id': '34dd833'} 

as mentioned above, doesn't work last one. should obvious why; if not, see rpartition(',') returns last value. can patch manually, or cheat packing , on end (entries = (a[1:-1] + ',').split(':')). if think it, if rsplit instead of rpartition, [0] right thing. let's instead.

so, how can clean bit?

first let's transform entries list of adjacent pairs. now, each each pair (n, nplus1), n.rpartition(',')[-1] key, , nplus1.rsplit(',', 1)[0] corresponding value. so:

>>> = "{user_id:34dd833,category:secondary,items:camera,vcr,dvd,type:sg_ser}" >>> entries = a[1:-1].split(':') >>> adjpairs = zip(entries, entries[1:]) >>> d = {k.rpartition(',')[-1]: v.rsplit(',', 1)[0] k, v in adjpairs} 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -