Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading