es6 将字符串转换为json,Javascript:将JSON字符串转换为ES6映射或其他形式以保留键的顺序...

Is there a native (built in) in ES6 (or subsequent versions), Javascript or in TypeScript method to convert a JSON string to ES6 map OR a self-made parser to be implemented is the option? The goal is to preserve the order of the keys of the JSON string-encoded object.

Note: I deliberately don't use the word "parse" to avoid converting a JSON string first to ECMA script / JavaScript object which by definition has no order of its keys.

For example:

{"b": "bar", "a": "foo" } //

I need:

{ b: "bar", a: "foo" } //

解决方案

UPDATE

The only thing that I do differently is to get the keys with regex to maintain the order

let j = "{\"b\": \"bar\", \"a\": \"foo\", \"1\": \"value\"}"

let js = JSON.parse(j)

// Get the keys and maintain the order

let myRegex = /\"([^"]+)":/g;

let keys = []

while ((m = myRegex.exec(j)) !== null) {

keys.push(m[1])

}

// Transform each key to an object

let res = keys.reduce(function (acc, curr) {

acc.push({

[curr]: js[curr]

});

return acc

}, []);

console.log(res)

ORIGINAL

If I understand what you're trying to achieve for option 2. Here's what I came up with.

let j = "{\"b\": \"bar\", \"a\": \"foo\"}"

let js = JSON.parse(j)

let res = Object.keys(js).reduce(function (acc, curr) {

acc.push({

[curr]: js[curr]

});

return acc

}, []);

console.log(res)

Basically get all the keys of the object, and then reduce it. What the reducer function convert each keys to an object

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值