0

I'm trying to change a list of values in a nested json and turn it into an array.

This is the current json output for two examples:

Example 1:
print(response['Version']['Document'])

{
    "Version": "0001",
    "Statement": {
        "Effect": "----",
        "Action": "----",
        "Resource": "*"
    }
}

Example 2:
print(response['Version']['Document'])
{
    "Version": "0002",
    "Statement": [
        {
            "Effect": "----",
            "Resource": "*"
        }
    ]
}

I want to change the Statement, that is a list of values (for example 1) into an array but the values inside (Effect, Action and Resource) stay as list values.

I'm trying to make an if statement that will respect the second example (Example 2) already being an array.

Desired output:

Example 1:
print(response['Version']['Document'])

{
    "Version": "0001",
    "Statement": [
        {
        "Effect": "----",
        "Action": "----",
        "Resource": "*"
        }
    ]
}

Example 2:
print(response['Version']['Document'])
{
    "Version": "0002",
    "Statement": [
        {
            "Effect": "----",
            "Resource": "*"
        }
    ]
}

What would be a good solution for this?

2 Answers 2

1

You can simply check for its datatype

    if (type(response['Version']['Document']['Statement'])==list):
        pass
    else:
        response['Version']['Document']['Statement']=[response['Version']['Document']['Statement']]
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this does exactly what I want it to. Thank you very much for both answers.
0

I think you just have to replace the item:

s = response['Version']['Document'][‘Statement’]
if not isinstance(s, list):
    response['Version']['Document'][‘Statement’] = [s]

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.