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

I receive the following JSON string from an API function.

"Inbound": {
    "callRelatedFields": ["ANI",
    "DNIS"],
    "objects": {
        "Contact": [{
            "displayName": "Name",
            "apiName": "Name"
        },
        {
            "displayName": "Email",
            "apiName": "Email"
        }],
        "Account": [{
            "displayName": "Account Name",
            "apiName": "Name"
        },
        {
            "displayName": "Phone",
            "apiName": "Phone"
        },
        {
            "displayName": "Fax",
            "apiName": "Fax"
        }],
        "cnx__Phone__c": [{
            "displayName": "Phone Name",
            "apiName": "Name"
        },
        {
            "displayName": "Phone Number Line 1",
            "apiName": "cnx__Phone_Number_Line_1__c"
        },
        {
            "displayName": "Phone Number Line 2",
            "apiName": "cnx__Phone_Number_Line_2__c"
        },
        {
            "displayName": "Type",
            "apiName": "cnx__Type__c"
        },
        {
            "displayName": "Location",
            "apiName": "cnx__Location__c"
        },
        {
            "displayName": "Call Manager",
            "apiName": "cnx__Call_Manager__c"
        },
        {
            "displayName": "Mac Address",
            "apiName": "cnx__Mac_Address__c"
        }]
    },
    "screenPopSettings": {
        "screenPopsOpenWithin": "ExistingWindow",
        "SingleMatch": {
            "screenPopType": "PopToEntity"
        },
        "NoMatch": {
            "screenPopType": "DoNotPop"
        },
        "MultipleMatches": {
            "screenPopType": "DoNotPop"
        }
    }
}

The order of the objects inside "objects" is important! But when i parse this JSON string with JSON.parse, the order of those objects is lost.

Is there any good way to keep the order of those objects after they are parsed.

I tried to manipulate the string and convert the whole "objects" into an array, but this turned out to become way too complicated and hacky.

Answers:

Answer

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.

Screenshot from Chrome devtools

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"]
Answer

Unfortunately object properties are unordered in JavaScript so you shouldn't rely on being able to iterate over them in a particular sequence.

I would suggest accessing the properties by name in the order you need them, rather than just iterating over the list.

Answer

As per the JSON standard, an object is unordered. So if you care about the order "Contact", "Account", "cnx__Phone__c", put them in an array ([]).

Maybe it's enough to put the property names themselves in an array next to the .objects themselves, so that you still can access them by their names. Many structures are valid solutions.

Answer

This solution works only if the properties and the data does not contain one of these characters: {, } and :.

Maybe you replace the curly brackets to square brackets and ": to #",. After that, you can the JSON string parse and get all objects replaced by arrays. The reading is: first value is the property (marked with # at the end) and the second value is the value.

The replacement machanism shuld be improved, in particular the replacement of ":, which can sometimes be wrong, and the search of the curly brackets.

var json = '{"Inbound":{"callRelatedFields":["ANI","DNIS"],"objects":{"Contact":[{"displayName":"Name","apiName":"Name"},{"displayName":"Email","apiName":"Email"}],"Account":[{"displayName":"Account Name","apiName":"Name"},{"displayName":"Phone","apiName":"Phone"},{"displayName":"Fax","apiName":"Fax"}],"cnx__Phone__c":[{"displayName":"Phone Name","apiName":"Name"},{"displayName":"Phone Number Line 1","apiName":"cnx__Phone_Number_Line_1__c"},{"displayName":"Phone Number Line 2","apiName":"cnx__Phone_Number_Line_2__c"},{"displayName":"Type","apiName":"cnx__Type__c"},{"displayName":"Location","apiName":"cnx__Location__c"},{"displayName":"Call Manager","apiName":"cnx__Call_Manager__c"},{"displayName":"Mac Address","apiName":"cnx__Mac_Address__c"}]},"screenPopSettings":{"screenPopsOpenWithin":"ExistingWindow","SingleMatch":{"screenPopType":"PopToEntity"},"NoMatch":{"screenPopType":"DoNotPop"},"MultipleMatches":{"screenPopType":"DoNotPop"}}}}';
json = json.replace(/{/g, '[').replace(/}/g, ']').replace(/"\:/g, '#",');
json = JSON.parse(json);
document.write('<pre>' + JSON.stringify(json, 0, 4) + '</pre>');

Answer

@GregL is right the JSON parsed came in alphabetic or in case of a number in ascending order and to keep the order you'll need an incremented number logic like:

var position_in_array = 0
var name = 'screenPopSettings'

object[`${position_in_array}${name}`] = value

position_in_array += 1
Answer

The parseJson returns data in object form and object doesn't has index. So we should define custom index of data array, if we want to keep the array index.

Example:

$arr[0] = array(
'Contact'=>array(
'key1'=>'val',
)
); 
$arr[1] = array(
'Account'=>array(
'key1'=>'val',
)
); 

It will produce the output as per the array index originally defined before parseJson function call.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.