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

如何避免JSON.parse解析时重排对象属性顺序

Hey there! Let me break down why this is happening and how you can fix it.

Why does JSON.parse reorder your keys?

This isn't actually JSON.parse being "uncooperative" — it's how JavaScript objects handle property ordering. When your object keys are strings that can be parsed as non-negative integers (like your "1", "2", "3"), JavaScript engines treat them like array indices. These keys get sorted in ascending numerical order, regardless of their original position in the JSON string.

That's why your parsed object ends up as {1: "salam", 2: "hoi", 3: "hi"} — the engine converts those string keys to integers and sorts them from smallest to largest.

How to keep the original key order

If preserving the exact order of keys from your JSON is important for your app, regular JavaScript objects aren't reliable here. Here are two solid solutions:

The most straightforward fix is to restructure your JSON into an array of key-value objects. Arrays guarantee order, so you'll never have this sorting issue again. For example:

'[{"key":"2","value":"hoi"},{"key":"3","value":"hi"},{"key":"1","value":"salam"}]'

Parsing this gives you an array that maintains the original order when you iterate over it:

const greetings = '[{"key":"2","value":"hoi"},{"key":"3","value":"hi"},{"key":"1","value":"salam"}]';
const parsedGreetings = JSON.parse(greetings);

parsedGreetings.forEach(item => {
  console.log(`${item.key}: ${item.value}`);
});
// Output:
// 2: hoi
// 3: hi
// 1: salam

2. Use a Map to preserve order (if you can't change the JSON)

If you can't modify the original JSON structure, you can use a Map (which preserves insertion order) — but you'll need to manually extract the original key order from the JSON string first, since Object.entries() will return sorted keys for integer-like strings.

Here's how to do it:

const greetings = '{"2":"hoi","3":"hi","1":"salam"}';

// Extract the original key order from the JSON string
const rawKeys = greetings.match(/"(\d+)":/g).map(match => match.slice(1, -2));
// Parse the JSON into an object
const parsedObj = JSON.parse(greetings);
// Build a Map using the original key order
const greetingsMap = new Map();
rawKeys.forEach(key => greetingsMap.set(key, parsedObj[key]));

// Iterate over the Map to get the original order
greetingsMap.forEach((value, key) => {
  console.log(`${key}: ${value}`);
});
// Output:
// 2: hoi
// 3: hi
// 1: salam

This is a bit of a workaround, though — restructuring the JSON into an array is cleaner and more maintainable long-term.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:42:48