Reputation: 21
I'm new to python scripting .I'm trying to parse a json key_value to stdout. Below is my script.Help me out in fixing below error.
pt="{'outval': 1.132805, 'max': 1.13283, 'to': 1534326908, 'bvalue': 1.13274, 'min': 1.132805, 'from': 1534326907, 'cvalue': 1.132825, 'at': 1534326907164488223, 'avalue': 1.13291, 'size': 1, 'aid': 1, 'vl': 0, 'id': 17777726}"
print(pt["outval"])
print(pt["to"])
print(pt["from"])
Error :
Traceback (most recent call last):
File "j.py", line 5, in <module>
print(pt["outval"])
TypeError: string indices must be integers, not str
Expected output:
1.132805
1534326908
1534326907
Thanks in advance
Upvotes: 0
Views: 69
Reputation: 21
Thanks Jon for the idea. I used ast.literal_eval to extract required key pair.Below is my updated code.
import json
import ast
pt="{'outval': 1.132805, 'max': 1.13283, 'to': 1534326908, 'bvalue': 1.13274, 'min': 1.132805, 'from': 1534326907, 'cvalue': 1.132825, 'at': 1534326907164488223, 'avalue': 1.13291, 'size': 1, 'aid': 1, 'vl': 0, 'id': 17777726}"
s=ast.literal_eval(pt)
print(s['outval'])
print(s['to'])
print(s['from'])
output :
root@lamp-1-vm:~/1# python j.py
1.132805
1534326908
1534326907
Upvotes: 1