Q:

Getting invalid json file by python for loop

hello first of all i'm trying to do a web scraper bot and then save all info in a json file
but when looping my json is invalid
this is part of my code and where i'm generating json
for tag in tags:
             myarr=tag.getText(strip=True)
             words=myarr.split()
             titles = []
             titles.append(words)
             data = [{"data": w} for w in zip(titles)]

             with open('data.json', 'a+',encoding='utf-8') as f:  

              json.dump(data, f,indent=2, ensure_ascii=False)

and this is part of my invalid json file that was been generated by python
[
  {
    "data": [
      [
        "Acuña",
        "Game",
        "GermánEspecialidad:Tratamiento",
        "del",
        "DolorLugar",
        "de",
        "Atención:Centro",
        "de",
        "Diagnóstico",
        "1"
      ]
    ]
  }
][
  {
    "data": [
      [
        "Aguayo",
        "Baeza",
        "EdgardoEspecialidad:Reumatología",
        "AdultosLugar",
        "de",
        "Atención:Centro",
        "de",
        "Diagnóstico",
        "1",
        "Piso",
        "7"
      ]
    ]
  }
]

while trying to parse this json on a online json parser it says SyntaxError: Unexpected token [ in JSON at position 318
is there anyway to generate a valid json?
if yes anyone that can help  me out?

A:

Python's json module doesn't directly support building a json file incrementally*.  Valid json can be generated by appending each each dict to a list, and then dumping the list to the output file, like this:
data = []
for tag in tags:
     myarr=tag.getText(strip=True)
     words=myarr.split()
     titles = []
     titles.append(words)
     data.extend({"data": w} for w in zip(titles))

# Once all the data has been processed, write to file.  
with open('data.json', 'w',encoding='utf-8') as f:  
    json.dump(data, f,indent=2, ensure_ascii=False)

* From the docs for json.dump: 

...trying to serialize multiple objects with repeated calls to dump() using the same fp will result in an invalid JSON file

