Home > Software engineering >  appending a json data with a list from another json
appending a json data with a list from another json

Time:12-22

var_data = {
        "a" : [ {
        "b" : {
            "c": [
                    {
                        "d": [
                            {
                                "e": {
                                    "f": "hello"
                                    
                                }
                               
                            }
                        ]
                    }
                ]

}
        }]
    }

i want to append var_data with a list under "d" array(y list). The list will be taken from another json(request json from POST in flask). below is the request json

{
    "a": "bcd",
    
    "w": [
        {
            "e": {
                "f": "hello"
            },
            "y": [
                {
                    
                    "z": "123"
                }
            ]
        }
    ]
}

also if the input field is an empty y array like "y": [] the var_data should also have the empty array "y":[] have tried the below took the array from the request in tobeappended_list

tobeappended_list=request_data["w"][0]["y"]

then

for j in range(len(tobeappended_list)):
        var_data["a"][0]["b"]["c"][0]["d"][0].append(tobeappended_list[j]["y"])

However it is throwing error like append is not a method for dictionary

EDITED

desired var_data

var_data = {
        "a" : [ {
        "b" : {
            "c": [
                    {
                        "d": [
                            {
                                "e": {
                                    "f": "hello"
                                    
                                },
                                "y": [
                {
                    
                    "z": "123"
                }
            ]
                               
                            }
                        ]
                    }
                ]

}
        }]
    }

CodePudding user response:

Indeed, you can't use append() with dictionaries. This var_data["a"][0]["b"]["c"][0]["d"][0] should return a list.

Here's a solution to your problem after your update and your comment.

tobeappended_list=request_data["w"][0]["y"]

var_data["a"][0]["b"]["c"][0]["d"][0]["y"] = []

for j in range(len(tobeappended_list)):
    var_data["a"][0]["b"]["c"][0]["d"][0]["y"].append(tobeappended_list[j])
  • Related