Replace JSON values in a doc python

Question:

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"
        }]
}
Asked By: dina robert

||

Answers:

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)
Answered By: OldBill
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.