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

后端 未结 6 1277
礼貌的吻别
礼貌的吻别 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:47

    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.

    0 讨论(0)
  • 2021-01-18 09:47

    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.

    0 讨论(0)
  • 2021-01-18 09:51

    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.

    0 讨论(0)
  • 2021-01-18 09:58

    @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
    
    0 讨论(0)
  • 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"]
    
    0 讨论(0)
  • 2021-01-18 09:59

    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>');

    0 讨论(0)
提交回复
热议问题