整个代码意味着扫描所有 json 文件(300+)并将 json 转换为 html。
但是有些标题有一些特殊字符,我先替换了那些。
但
Traceback (most recent call last):
File ".\json2html.py", line 30, in <module>
d["title"] = re.sub("[|\^&+\-%*?/=!>]", "-", d["title"])
TypeError: string indices must be integers
我已经用谷歌搜索了 3 个小时,但我的情况没有解决方案,例如这个: Parsing JSON with Python: TypeError: list indices must be integers, not str
Python 和 JSON - TypeError 列表索引必须是整数而不是 str
我的代码:
import json
import re
from glob import glob
for file_name in glob("*.json"):
fi = open(file_name, 'r')
data = json.load(fi)
for a in data.values():
for d in a:
d["title"] = re.sub("[|\^&+\-%*?/=!>]", "-", d["title"])
fo = open(data["title"] + ".html", 'w')
fo.write(str(data["body_html"]))
fi.close()
fo.close()
我试过了 :
for a in data:
a["title"] = re.sub("[|\^&+\-%*?/=!>]", "-", a["title"])
但还是报错。
试过:
dataTitle = data[0]["title"]
dataTitle = re.sub("[|\^&+\-%*?/=!>]", "-", dataTitle )
fo = open(dataTitle + ".html", 'w')
仍然有错误:
Traceback (most recent call last):
File ".\json2html.py", line 28, in <module>
dataTitle = data[0]["title"]
KeyError: 0
杰森:
{
"body_html": "<div><head></head><body><div class=\"lake-content-editor-core lake-engine lake-typography-traditional\" data-lake-element=....</a></div></div></body></div>",
"slug": 6643849,
"title": "idea/project?task->things<-tools%"
}
示例 json 文件: https ://www.dropbox.com/s/ks9cc1qzegc7t5j/cq4coz.json?dl=0