Search code examples
pythondocxpython-docx

Replace JSON values in a doc python


I want to replace a json values in a doc using python, I tried this code using a list, but it didn't work with my json form.

This is my code :

from docx import Document
#open the document
doc=Document('./test.docx')
Dictionary = {"#prenom#": "Dina", "#nom#":"Robert"}
for i in Dictionary:
    for p in doc.paragraphs:
        if p.text.find(i)>=0:
            p.text=p.text.replace(i,Dictionary[i])
#save changed document
doc.save('./test.docx')

And this is my JSON that I want to use :

{
    "data": [{
            "variable": "#prenom#",
            "value": "Dina"
        },
        {
            "variable": "#nom#",
            "value": "Robert"
        }]
}

Solution

  • You just need to iterate over the dictionaries within the JSON "data" key as follows:

    from docx import Document
    
    J = {
        "data": [{
            "variable": "#prenom#",
            "value": "Dina"
        },
            {
                "variable": "#nom#",
                "value": "Robert"
        }]
    }
    
    FILE = 'test.docx'
    
    doc = Document(FILE)
    
    for p in doc.paragraphs:
        for d in J['data']:
            if p.text.find(d['variable']) >= 0:
                p.text = p.text.replace(d['variable'], d['value'])
    
    doc.save(FILE)