loading dictionary from a file

Amit Gupta emailamit at gmail.com
Wed Feb 6 21:06:26 EST 2008


On Feb 6, 5:33 pm, Ben Finney <bignose+hates-s... at benfinney.id.au>
wrote:
> Amit Gupta <emaila... at gmail.com> writes:
> > Need a python trick, if it exists:
>
> > I have a file that stores key, value in following format
> > --
> > "v1" : "k1",
> > "v2" : "k2"
> > --
>
> > Is there a way to directly load this file as dictionary in python.
>
> That input looks almost like valid JSON <URL:http://json.org/>.
>
> If you can easily massage it into JSON format, you can use the Python
> JSON library <URL:http://cheeseshop.python.org/pypi/python-json>:
>
>     import json
>
>     input_text = open('foo.txt').read()
>     input_json = "{%(input_text)s}" % vars()
>
>     reader = json.JsonReader()
>     data = reader.read(input_json)
>
> If the 'input_json' above actually is valid JSON, that will give the
> corresponding Python data object.
>
> This avoids the massive security hole of performing 'eval' on
> arbitrary user input; the input isn't executed, merely parsed (as
> JSON) to create a data object.
>
> --
>  \      "I busted a mirror and got seven years bad luck, but my lawyer |
>   `\                        thinks he can get me five." --Steven Wright |
> _o__)                                                                  |
> Ben Finney

Great Inputs from both the posters.

Thanks



More information about the Python-list mailing list