首页 > 解决方案 > 通过python for循环获取无效的json文件

问题描述

你好首先我正在尝试做一个网络爬虫机器人然后将所有信息保存在一个json文件中但是当循环我的json是无效的

这是我的代码的一部分,我正在生成 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)

这是我由python生成的无效json文件的一部分

[
  {
    "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"
      ]
    ]
  }
]

尝试在在线 json 解析器上解析此 json 时,它显示 SyntaxError: Unexpected token [ in JSON at position 318

反正有生成有效的json吗?如果是的话,有人可以帮助我吗?

标签: pythonjsonscreen-scraping

解决方案


Python 的 json 模块不直接支持增量构建 json 文件* . 可以通过将每个字典附加到列表中来生成有效的 json,然后将列表转储到输出文件中,如下所示:

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)

*来自json.dump的文档:

...尝试使用相同的 fp 重复调用 dump() 来序列化多个对象将导致无效的 JSON 文件


推荐阅读