Python3 json.load()读取JSON文件顺序异常,树莓派上如何解决?
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
dicttype preserves insertion order, sojson.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,
dictis unordered by default—sojson.load()rearranges keys arbitrarily, andjson.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

