0

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

This is the current json output:

print(response['Version']['Document'])

{
    "Statement": [
        {
            "ID": "000"
            "Resource": [
                "a----",
                "b----"
            ]
        }
        {
            "Resource": "c----"
        }
        {
            "ID": "000"
            "Resource": [
                "d----",
                "e----"
            ]
        }
    ]
}

I want to turn the value "Resource": "c----" into an array, so the desired output would look like this:

{
    "Statement": [
        {
            "ID": "000"
            "Resource": [
                "a----",
                "b----"
            ]
        }
        {
            "Resource": [
                "c----"
            ]
        }
        {
            "Resource": [
                "d----",
                "e----"
            ]
        }
    ]
}

What would be a good solution for this?

1 Answer 1

0

First You can find data type of variable by using type() and check if variable is of type list then its okay and if not then you can convert it to list.

You can use following piece of code

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

5 Comments

Yes, this works. I have another similar problem, where the 'Statement' itself is a list. Can you look at the edit? Otherwise I'm accepting the answer and posting another question.
Please take a look at my new post: stackoverflow.com/questions/65425495/…
you can apply similar approach to your another problem. I will make a comment on your other question.
I'm trying to apply it but having a bit of trouble. Please do make a comment :) I already accepted your answer
please check my answer on your other question. may be it will help you

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.