0

In my application I am receiving a string 'abc[0]=123'

I want to convert this string to an array of items. I have tried eval() it didnt work for me. I know the array name abc but the number of items will be different in each time.

I can split the string, get array index and do. But I would like to know if there is any direct way to convert this string as an array insert. I would greately appreciate any suggestion.

7
  • eval should work - but it would be incredibly dangerous to use eval to process external input in this way. Personally I would split the string (or use a regex). Commented Jan 21, 2013 at 10:57
  • 1
    In my application I am receiving a string 'abc[0]=123' . What sort of application is this, which receives an assignment statement? Commented Jan 21, 2013 at 10:57
  • @Abhijit it doesn't matter, which application is generating it? Anyways i will suggest to use regex. Commented Jan 21, 2013 at 11:00
  • 1
    @Netro: It does matter. May be he is solving the wrong problem. Commented Jan 21, 2013 at 11:01
  • Can you provide an example with more than one item? Commented Jan 21, 2013 at 11:03

3 Answers 3

1

are you looking for something like

In [36]: s = "abc[0]=123"

In [37]: vars()[s[:3]] = []

In [38]: vars()[s[:3]].append(eval(s[s.find('=') + 1:]))

In [39]: abc
Out[39]: [123]

But this is not a good way to create a variable

Sign up to request clarification or add additional context in comments.

Comments

1

Here's a function for parsing urls according to php rules (i.e. using square brackets to create arrays or nested structures):

import urlparse, re

def parse_qs_as_php(qs):

    def sint(x):
        try:
            return int(x)
        except ValueError:
            return x

    def nested(rest, base, val):
        curr, rest = base, re.findall(r'\[(.*?)\]', rest)
        while rest:
            curr = curr.setdefault(
                sint(rest.pop(0) or len(curr)), 
                {} if rest else val)
        return base

    def dtol(d):
        if not hasattr(d, 'items'):
            return d
        if sorted(d) == range(len(d)):
            return [d[x] for x in range(len(d))]
        return {k:dtol(v) for k, v in d.items()}

    r = {}
    for key, val in urlparse.parse_qsl(qs):
        id, rest = re.match(r'^(\w+)(.*)$', key).groups()
        r[id] = nested(rest, r.get(id, {}), val) if rest else val
    return dtol(r)

Example:

qs = 'one=1&abc[0]=123&abc[1]=345&foo[bar][baz]=555'
print parse_qs_as_php(qs)
# {'abc': ['123', '345'], 'foo': {'bar': {'baz': '555'}}, 'one': '1'}

Comments

0

Your other application is doing it wrong. It should not be specifying index values in the parameter keys. The correct way to specify multiple values for a single key in a GET is to simply repeat the key:

http://my_url?abc=123&abc=456

The Python server side should correctly resolve this into a dictionary-like object: you don't say what framework you're running, but for instance Django uses a QueryDict which you can then access using request.GET.getlist('abc') which will return ['123', '456']. Other frameworks will be similar.

1 Comment

Actually I am working with a facebook application. After send the application request. Facbook is returning the values in this format. So you cant say it is wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.