Keep order of objects inside a JSON String after they are parsed

后端 未结 6 1284
礼貌的吻别
礼貌的吻别 2021-01-18 09:42

I receive the following JSON string from an API function.

\"Inbound\": {
    \"callRelatedFields\": [\"ANI\",
    \"DNIS\"],
    \"objects\": {
        \"Con         


        
6条回答
  •  暖寄归人
    2021-01-18 09:59

    I have a suspicion that the thing that makes you think the keys have changed order is that Chrome devtools show objects with their keys sorted in alphabetical order. Whereas if you use Object.keys() or the equivalent JS to manually iterate through the keys, you will find they come out in the order they were defined in the JSON string.

    Here is the equivalent JS for Object.keys():

    function objectKeys(obj) {
        var keys = [];
        if (!obj) return keys;
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                keys.push(key);
            }
        }
    }
    

    When I call this with the objects part of the parsed object I get the following array:

    ["Contact", "Account", "cnx__Phone__c"]
    

提交回复
热议问题