1

I have a sample json:

enter image description here

I want to use the json module of python and recurse through to find the "MaxSize" in "pevcwebasg". Have the following code:

import json

param_file_handle = json.load(open("sample.json"))
print param_file_handle['Resources']['pevcwebasg']['Type']
resources = param_file_handle['Resources']
for asg in resources:
     print asg["Type"]

The out put of which is :

> AWS::AutoScaling::AutoScalingGroup Traceback (most recent call last): 
> File "test.py", line 8, in <module>
>     print asg['Type'] TypeError: string indices must be integers

What I dont get is this line "print param_file_handle['Resources']['pevcwebasg']['Type']" works fine and gets me the output but when i recurse through and try and find asg["Type"], it fails. Any better way to do this ? I need to recurse through the tree and find the value.

Edit 1:

as I do recurse through values, I get stuck with error.

param_file_handle = json.load(open("sample.json"))
resources = param_file_handle['Resources']
for asg in resources.values():
     if asg["Type"] == "AWS::AutoScaling::AutoScalingGroup":
          for values in asg['Properties']:
              print values["MaxSize"]

error :

Traceback (most recent call last):
  File "test.py", line 9, in <module>
    print values["MaxSize"]
TypeError: string indices must be integers
2
  • next time, please paste text instead of posting pictures Commented Dec 23, 2015 at 14:27
  • it was a huge json, didn't want it to take the whole space so just used the pic. I know I could have trimmed it. Will do. Commented Dec 23, 2015 at 14:30

3 Answers 3

3
for asg in resources:

This iterates through the keys of resources, rather than the values. Try:

for asg in resources.values():
Sign up to request clarification or add additional context in comments.

3 Comments

I would do keys() instead of values() so you have the option to reproduce the content of the key which meets your Criteria.
@rajesh.kanakabandi and owner of the post - take a look at the edit
you dont need the inner for loop. when you want to Access the MaxSize.
1
param_file_handle = json.load(open("sample.json"))
resources = param_file_handle['Resources']
for asg in resources.values():
     if asg["Type"] == "AWS::AutoScaling::AutoScalingGroup":
          print asg["Properties"]["MaxSize"]

try this.

Comments

0

you broke hirerchy, missed "pevcwebasg"

resources = param_file_handle['Resources']['pevcwebasg']
for asg in resources:
     print asg["Type"]

Comments

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.