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

Python3 json.load()读取JSON文件顺序异常,树莓派上如何解决?

Fixing JSON Order Issues on Raspberry Pi with json.load() and json.dump()

Hey there! Let's break down why you're seeing different JSON ordering behavior between Windows and Raspberry Pi, and how to fix it.

The Root Cause

The key difference here is Python version support for ordered dictionaries:

  • On Windows, your Python version is likely 3.7 or newer. Starting in Python 3.7, the native dict type preserves insertion order, so json.load() automatically retains the order of keys from your original JSON file.
  • On your Raspberry Pi, you're probably running a Python version older than 3.7. In these versions, dict is unordered by default—so json.load() rearranges keys arbitrarily, and json.dump() writes them in that same jumbled order.

Solution 1: Use OrderedDict (Compatible with All Python Versions)

If upgrading Python isn't an option, you can use collections.OrderedDict to enforce key order when loading and saving JSON. This works on any Python version:

import json
from collections import OrderedDict

# Load JSON while preserving key order
with open("your_file.json", "r") as input_file:
    # object_pairs_hook ensures we keep the original key order
    ordered_data = json.load(input_file, object_pairs_hook=OrderedDict)

# Save the ordered data back to JSON
with open("output_file.json", "w") as output_file:
    # json.dump will respect the OrderedDict's order
    json.dump(ordered_data, output_file, indent=4)

Solution 2: Upgrade Python on Raspberry Pi to 3.7+

If you can update your Raspberry Pi's Python environment, upgrading to version 3.7 or newer lets you use the native dict with order preservation. After upgrading, your original code (just json.load() and json.dump()) will work exactly like it does on Windows—no extra parameters needed.

A quick note: Make sure you're not using sort_keys=True in json.dump()—that parameter forces alphabetical sorting, which would override any ordered behavior. The default value is False, so you should be good unless you explicitly set it.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:59:25