Basically I need to get the json content of a file, replace a variable and then append it with a new dictionary. I’ve tried in every way and searched but I can’t find a solution. *The first line exemplifies the data that comes from the .json file
liststr = [{"type": "divider"},{"type": "section","text": {"type": "mrkdwn","text": "Olá {user} :wave:\n\n Segue abaixo a listagem de colaboradores terceiro sob sua gestão e a data de expiração da conta. \n\nA data de expiração máxima para a conta é de 30 dias. Caso o período de renovação exceda esse limite, a data será fixada em D+30. "}}]
liststr = str(liststr)
liststr = liststr.replace("{user}", "Bruno")
listlist = json.loads(json.dumps(liststr))
print(listlist)
Even that part works fine. The issue is that as I said, I need to append with one more information, for example:
liststr = [{"type": "divider"},{"type": "section","text": {"type": "mrkdwn","text": "Olá {user} :wave:\n\n Segue abaixo a listagem de colaboradores terceiro sob sua gestão e a data de expiração da conta. \n\nA data de expiração máxima para a conta é de 30 dias. Caso o período de renovação exceda esse limite, a data será fixada em D+30. "}}]
liststr = str(liststr)
liststr = liststr.replace("{user}", "Bruno")
listlist = json.loads(json.dumps(liststr))
listlist.append({
"user": "bruno"
})
print(listlist)
I get the error message
"AttributeError: ‘str’ object has no attribute ‘append’"
because it considers the json.loads variable to be str instead of list. I’ve tried converting it to a list but it doesn’t work either.
>Solution :
def replace(v, needle, replacement):
if isinstance(v, str):
return v.replace(needle, replacement)
if isinstance(v, list):
return [replace(i, needle, replacement) for i in v]
if isinstance(v, dict):
return {k: replace(i, needle, replacement) for k, i in v.items()}
return v
l = [{"type": "divider"},{"type": "section","text": {"type": "mrkdwn","text": "Olá {user} :wave:\n\n Segue abaixo a listagem de colaboradores terceiro sob sua gestão e a data de expiração da conta. \n\nA data de expiração máxima para a conta é de 30 dias. Caso o período de renovação exceda esse limite, a data será fixada em D+30. "}}]
l = replace(l, '{user}', 'buno')
This is what you’re trying to do. Recursively iterate over all values in the list of dicts, and replace the string "{user}" in any of them, all the while keeping everything as a list of dicts and not turning everything into a string.