如何在Python中将网页提取的字符串转为可被前端映射的JSON数组
生成可被React map遍历的JSON数组解决方案
问题根源
你当前生成的是JSON对象(键值对结构),但React的map()方法仅支持遍历数组类型的数据,所以无法直接遍历。需要将Python端的结果存储结构从字典改为列表,最终输出JSON数组。
修改后的Python代码
1. 初始化存储结构
将原来的字典替换为列表:
# 初始化空列表用于存储结果 results_list = [] i = 0 # 初始化计数器,确保从1开始计数
2. 遍历解析结果并填充列表
在循环中直接生成单个结果对象,追加到列表中,同时添加_id字段(对应React组件的key):
for res in parsed_html.body.find_all_next('li', attrs={'class': 'result'}): i = i + 1 titel = str(res.find('a').text) description = str(res.find('p').text) # 合并字符串处理操作,简化代码 description = description.strip().replace("<p>", "").replace("<br>", "") link = str(res.find('cite').text) lastCheckd = str(res.find('span').text) # 构造单个结果对象 result_item = { "_id": i, "titel": titel.strip(), "description": (description[:75] + '..') if len(description) > 75 else description, "link": link.strip(), "lastCheckd": lastCheckd.strip(), "status": "unknown" } # 将对象追加到列表 results_list.append(result_item)
3. 序列化为JSON数组
import json # 将列表序列化为JSON格式 serialized_json = json.dumps(results_list)
生成的JSON示例
[ { "_id": 1, "titel": "hello, anon.", "description": "hello, anon - Uncensored Onion ", "link": "LINK", "lastCheckd": "1, 3 ago", "status": "unknown" }, { "_id": 2, "titel": "Hello", "description": "No description provided", "link": "LINK", "lastCheckd": "2, 1 ago", "status": "unknown" } ]
前端适配说明
现在前端接收的link变量是标准数组,可以直接使用map()遍历,每个项的_id字段正好作为React组件的key属性,匹配你现有前端代码的需求。
内容的提问来源于stack exchange,提问作者Mustapha
相关产品推荐
相关产品推荐

