Tushar Raichand
Tushar Raichand

Reputation: 61

Accessing values in json using python

I have a JSON string as below

typ_json="{'FromPort': 80, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'Ipv6Ranges': [{'CidrIpv6': '::/0'}], 'PrefixListIds': [], 'ToPort': 80, 'UserIdGroupPairs': []}"

I want to access FromPort and ToPort Values.

I have tried print(typ_json['FromPort'])

But I get the error:

TypeError: list indices must be integers or slices, not str

Upvotes: 0

Views: 93

Answers (3)

Yash Shukla
Yash Shukla

Reputation: 141

import json
import ast

typ_json="{'FromPort': 80, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'Ipv6Ranges': [{'CidrIpv6': '::/0'}], 'PrefixListIds': [], 'ToPort': 80, 'UserIdGroupPairs': []}"

port = ast.literal_eval(typ_json)
print(port['FromPort'])

Upvotes: -1

han solo
han solo

Reputation: 6590

That is not valid JSON. You need to replace the quotes and load the resulting string like,

>>> import json
>>> typ_json
"{'FromPort': 80, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'Ipv6Ranges': [{'CidrIpv6': '::/0'}], 'PrefixListIds': [], 'ToPort': 80, 'UserIdGroupPairs': []}"
>>> x = typ_json.replace("'", '"')
>>> json.loads(x) # now it is a `dict` and you can access the values
{u'PrefixListIds': [], u'FromPort': 80, u'IpRanges': [{u'CidrIp': u'0.0.0.0/0'}], u'ToPort': 80, u'IpProtocol': u'tcp', u'UserIdGroupPairs': [], u'Ipv6Ranges': [{u'CidrIpv6': u'::/0'}]}
>>> json.loads(x)['FromPort']
80

Upvotes: 0

Jeril
Jeril

Reputation: 8521

you need to convert the json to dictionary

import json
data = json.loads(typ_json)
print(data['FromPort'])

Sometimes json might give some error. In that case you can use ast.literal_eval

import ast
data = ast.literal_eval(typ_json)
print(data['FromPort'])

Upvotes: 3

Related Questions