1

I'm getting some data from a file, which looks like this:

[200, "Hello", "World"]

Now, since this is a file, this array is inside a string; I turn it into an array using eval(). This works fine BUT the integer at the start is converted to an ascii char, instead of an integer as I want it to (the euro sign).

How can I fix this?

2
  • 2
    This worked fine for me. >>> z = eval("[200, \"hello\", \"world\"]") >>> z [200, 'hello', 'world'] Commented Jul 21, 2011 at 8:47
  • @Judge John Deed ascii char ? Which ascii char ? I don't observe what you describe Commented Jul 21, 2011 at 8:47

2 Answers 2

2

You could use the simplejson module. E.g.

>>> import simplejson
>>> a = simplejson.loads('[200, "Hello", "World"]')
>>> print a
[200, 'Hello', 'World']

This way "malicious" data such as os.execvp() would not be evaluated but an JSONDecodeErrorwould be thrown.

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

Comments

2

You can use literal_eval. Really depends on the source - is the source speaking Python or JSON - there is a lot of overlap where they have identical representations

>>> from ast import literal_eval
>>> literal_eval('[200, "Hello", "World"]')
[200, 'Hello', 'World']

Comments

Your Answer

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