python - 通过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吗?如果是的话,有人可以帮助我吗?
解决方案
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 文件
推荐阅读
- python - 如何为泡菜对象使用 requirements.txt 或类似文件
- html - 带有 viewBox 和 preserveAspectRatio="none" 的 SVG 元素,其中 rect 仅随容器 div 的宽度缩放
- google-apps-script - 当我使用 App 脚本创建时,Google 日历活动关闭了一天
- angular - 选择下拉项目并以角度 7 关闭后,弹出窗口不清除
- swift - 点击节点时如何防止崩溃
- android - httpclient 定义了与 Android 现在提供的类冲突的类
- c# - WPF 将 TabControl 项内容绑定到不同的数据模板
- azure-data-studio - 我们可以更改“新查询”名称模板吗?
- java - Java同步:多个CountDownLatch
- sms - 有谁知道 Spectrum Mobile 的 SMS 网关,我可以使用 SMTP 吗?