Javascript:将JSON字符串转换为ES6映射或其他形式以保留键的顺序 [英] Javascript: Convert a JSON string into ES6 map or other to preserve the order of keys

查看:94
本文介绍了Javascript:将JSON字符串转换为ES6映射或其他形式以保留键的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在ES6(或后续版本),Javascript或TypeScript方法中使用本机(内置)将JSON字符串转换为ES6映射,或者选择要实现的自制解析器?目标是保留JSON字符串编码对象的键顺序.

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.

注意:我故意不使用"parse"一词来避免首先将JSON字符串转换为ECMA脚本/JavaScript对象,该对象按照定义没有键的顺序.

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.

例如:

{"b": "bar", "a": "foo" }        // <-- This is how the JSON string looks

我需要:

{ b: "bar", a: "foo" }           // <-- desired (map version of it)

推荐答案

更新

https://jsbin.com/kiqeneluzi/1/edit?js,console

我唯一不同的方法是使用正则表达式获取密钥以保持顺序

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)


原始

如果我了解您要为选项2达到的目标,这就是我的想法.

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

https://jsbin.com/pocisocoya/1/edit?js,console

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)

基本上获取对象的所有键,然后将其还原. reducer函数将每个键转换为对象的方式

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

这篇关于Javascript:将JSON字符串转换为ES6映射或其他形式以保留键的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆