I wrote my first Python script (note: I am new to Python) and I am trying to parse some JSON string in order to retrieve a value related to a particular JSON key but I am in trouble.
In my script.py
file I have the following:
data = '{ "key1": "152", "key2": "da8fb07ace5512", "key3": "cfed379e13aebc" }'
data_decoded = json.load(data)
data["key1"]
When I run the above script with the command python script.py
then I get:
Traceback (most recent call last):
File "/script.py", line 2, in <module>
data_decoded = json.load(data)
File "/usr/lib/python2.7/json/__init__.py", line 274, in load
return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'
How can I solve the problem? I expect that the returned value is 152
.
UPDATE (after commenting)
If I use loads()
then I get:
Traceback (most recent call last):
File "/script.py", line 3, in <module>
data["key1"]
TypeError: string indices must be integers, not str
I don't care if it is a string or a integer. I would like just to retrieve the value.
json.loads()
instead ofjson.load()
- parses a string instead of a file stream. – Dietrich Apr 12 '14 at 12:06