#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2006
    Posts
    63
    Rep Power
    13

    How to convert a string to dictionary?


    Suppose I have a string:

    a = "{'a': 'hi', 'b': 'there'}"

    Does anyone have a clever way to convert that to a dictionary?

    I tried the following:

    exec ("b=a")

    pickle.loads(a)

    Neither method works. Can anyone suggest something?

    I'm trying to convert the results from the google ajax api to a dictionary. The results are in the perfect format, but I can't get Python to evaluate them as a dictionary.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2006
    Posts
    63
    Rep Power
    13
    Gar, that was silly. Figured it out:

    exec ("b=" + a)
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2008
    Posts
    13
    Rep Power
    0
    Originally Posted by wrybread
    Gar, that was silly. Figured it out:

    exec ("b=" + a)
    Another way to do the same thing:

    Code:
    b = eval(a)
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1376
    either exec or eval will work, but both are unsafe if you do not have complete control over the strings that are passed - someone could craft a string that could damage or take control of your server. I think eval is safer is this regard, since it will only evaluate a single expression while exec will execute an arbitrary block of python code.

    For example (don't run this!)
    Code:
    a = "{}; import shutil; shutil.rmtree('/', True)"
    exec ("b=" + a)
    # bye bye system...
    I presume the Google Ajax API uses JSON, in which case the safest option is to use the JSON library. This is included in the Python 2.6 libraries, and can be downloaded for earlier versions.

    Dave

IMN logo majestic logo threadwatch logo seochat tools logo