本文介绍了按Asc顺序对JS对象进行字符串化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似js的对象

I have an js object like

{
  a: 1,
  b: 2,
  c: 3
}

我想使用JSON.stringify以相同的顺序对上述对象进行字符串化.这意味着,stringify应该向我返回如下字符串,

I wanted to stringify the above object using JSON.stringify with the same order. That means, the stringify should return me the strings as below,

"{"a":"1", "b":"2", "c":"3"}"

但是,如果我的js对象具有太多的属性(例如,超过500个),则会像下面这样返回我

But it is returning me like the below one if my js object has too many properties say more than 500,

"{"b":"2", "a":"1", "c":"3"}"

是否有任何选择来获取我的js对象的json字符串(按升序排序).

Is there any option to get my js object's json string as in sorted in asc.

推荐答案

如果该命令对您很重要,请不要使用JSON.stringify,因为该命令并不安全,因此可以使用javascript创建JSON字符串化,为了处理字符串值,我们有2种不同的方法,首先使用regexp替换无效字符或使用JSON.stringify作为我们的值,例如,如果我们有类似'abc\d"efg'的字符串,我们可以简单地得到正确的结果JSON.stringify('abc\d"efg'),因为此函数的整体思路是按照正确的顺序进行字符串化:

If the order is important for you, don't use JSON.stringify because the order is not safe using it, you can create your JSON stringify using javascript, to deal with string values we have 2 different ways, first to do it using regexp an replace invalid characters or using JSON.stringify for our values, for instance if we have a string like 'abc\d"efg', we can simply get the proper result JSON.stringify('abc\d"efg'), because the whole idea of this function is to stringify in a right order:

function sort_stringify(obj){
    var sortedKeys = Object.keys(obj).sort();
    var arr = [];
    for(var i=0;i<sortedKeys.length;i++){
        var key = sortedKeys[i];
        var value = obj[key];
        key = JSON.stringify(key);
        value = JSON.stringify(value);
        arr.push(key + ':' + value);
    }
    return "{" + arr.join(",\n\r") + "}";
}
var jsonString = sort_stringify(yourObj);

如果我们不想使用JSON.stringify解析键和值来执行此操作,则解决方案将是:

If we wanted to do this not using JSON.stringify to parse the keys and values, the solution would be like:

function sort_stringify(obj){
    var sortedKeys = Object.keys(obj).sort();
    var arr = [];
    for(var i=0;i<sortedKeys.length;i++){
        var key = sortedKeys[i];
        var value = obj[key];
        key = key.replace(/"/g, '\\"');
        if(typeof value != "object")
            value = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
        arr.push('"' + key + '":"' + value + '"');
    }
    return "{" + arr.join(",\n\r") + "}";
}

这篇关于按Asc顺序对JS对象进行字符串化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 04:26