如何将长URL元组列表转换为指定结构的JSON对象?
解决方案
情况1:输入是直接存储URL的元组
如果你的输入是类似 ("https://example.com/1", "https://example.com/2", "https://example.com/3") 的元组,用列表推导式快速转换结构,再通过json模块生成目标JSON:
import json # 你的URL元组 url_tuples = ("https://example.com/page1", "https://example.com/page2", "https://example.com/page3") # 构造目标结构 result = { "links": [{"src": url} for url in url_tuples] } # 生成格式化的JSON json_result = json.dumps(result, indent=4) print(json_result)
情况2:输入是包含单元素元组的列表
如果输入是 [("https://example.com/1",), ("https://example.com/2",)] 这种格式,只需在推导时取出元组的第一个元素:
import json # 你的单元素元组列表 url_tuple_list = [("https://example.com/page1",), ("https://example.com/page2",), ("https://example.com/page3",)] # 构造目标结构 result = { "links": [{"src": item[0]} for item in url_tuple_list] } # 生成格式化的JSON json_result = json.dumps(result, indent=4) print(json_result)
输出结果
两种情况最终都会生成你需要的JSON格式:
{ "links": [ { "src": "https://example.com/page1" }, { "src": "https://example.com/page2" }, { "src": "https://example.com/page3" } ] }
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

