You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将多个Python列表转为指定格式JSON文件并存储到树莓派存储设备

Python列表转目标JSON并保存到树莓派的实现方案

你可以直接用Python标准库自带的json模块完成需求,注意你给出的示例JSON用了单引号,这不符合官方JSON规范(标准JSON要求字符串使用双引号),如果只是笔误优先使用以下标准实现:


标准实现代码(推荐,符合JSON规范)

import json

# 你现有的6个列表
dows=['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
dates=['10-4', '10-5', '10-6', '10-7', '10-8']
maxs=['24', '23', '17', '16', '18']
mins=['13', '13', '11', '10', '7']
precipitation_probabilities=['0', '0', '76', '70', '21']
wind_speeds=['13', '21', '16', '8', '11']

# 组装为对应结构的Python字典
weather_data = {
    "dows": dows,
    "dates": dates,
    "maxs": maxs,
    "mins": mins,
    "precipitation_probabilities": precipitation_probabilities,
    "wind_speeds": wind_speeds
}

# 写入树莓派磁盘,示例路径为pi用户家目录下的weather.json,可自行修改存储路径
save_path = "/home/pi/weather.json"
with open(save_path, "w", encoding="utf-8") as f:
    # indent=4参数控制缩进格式,和你预期的排版完全一致
    json.dump(weather_data, f, indent=4, ensure_ascii=False)

特殊场景:强制输出单引号(不符合JSON标准,仅适配特殊要求)

如果你的使用场景必须要求使用单引号,可以用以下代码处理:

import json

# 列表定义、字典组装部分和上方代码完全一致
# ...省略重复代码...

save_path = "/home/pi/weather.json"
# 先生成标准JSON字符串,再批量替换双引号为单引号
json_str = json.dumps(weather_data, indent=4, ensure_ascii=False).replace('"', "'")
with open(save_path, "w", encoding="utf-8") as f:
    f.write(json_str)

验证方式

运行代码后,你可以在树莓派终端执行以下命令查看生成的文件内容:
cat /home/pi/weather.json

内容的提问来源于stack exchange,提问作者RoSi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 02:39:04