0

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

3
  • I'd also recommend that you use typ_json.get(key) instead of directly accessing the key, as it might not exist. Commented Apr 16, 2019 at 12:20
  • That's not valid JSON. It looks like a Python dictionary converted to str. Commented Apr 16, 2019 at 12:24
  • The question and the error is misleading. TypeError: list indices must be integers or slices, not str suggests it is a list, but what you showed is a str Commented Apr 16, 2019 at 12:48

3 Answers 3

3

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'])
Sign up to request clarification or add additional context in comments.

Comments

0

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

4 Comments

I get this error AttributeError: 'dict' object has no attribute 'replace'
Then your typ_json was already a dict then. But what you showed in the question, suggested it was an str
Assuming it is already a dict how can i access FromPort Value?
typ_json['FromPort'] will give you that
-1
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'])

2 Comments

how is this different from the other answer?
I didn't see your answer, so I thought it should be the right answer.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.