Oder of my json request is getting sorted in alphabetical order when i am getting data from data file.i dnt want my json request to get sorted

旧街凉风 提交于 2021-01-29 12:38:01

问题


{
   "ID":0,
   "OrganizationId":"",
   "OrganizationName":"",
   "Name":"",
   "IsActive":"True",
   "Type":2,
   "AppliesTo":1,
   "TagHOD":"",
   "DisplayAsPrimary":"false",
   "Values":[

   ]
}

Above is my json request which I have stored in a data file

Below is my json request body which I am getting after sending a parameter into it. It is sorted into alphabetical order which I don't want. I want the same order as above eg ID Should be first then OrganizationId

{
    "AppliesTo": 1,
    "DisplayAsPrimary": "false",
    "ID": 0,
    "IsActive": "True",
    "Name": "TAG1205510333275",
    "OrganizationId": 2404,
    "OrganizationName": "",
    "TagHOD": "",
    "Type": 2,
    "Values": [
        {
            "HODEmail": "tagsapiautomationae@mailinator.com",
            "Id": 1,
            "IsDeleted": false,
            "Text": "Level20"
        }
    ]
}

回答1:


The JSON specification states: "An object is an unordered set of name/value pairs."

When working with JSON (and objects in most languages), the properties in objects are inherently unordered. You can't rely on different systems giving you the properties in the same order you supply them. In fact, you can't even rely on a single system giving you the properties in the same order all the time within a given execution of the code, even though many systems do behave that way.

If you want to preserve ordering, you either need to use an array to store the data, or you can use an array of object property names that stores the keys in the order you want, so you can use that array to reference them in the desired order later.

EG:

   keyorder = ["ID",
               "OrganizationId",
               "OrganizationName",
               "Name",
               "IsActive",
               "Type",
               "AppliesTo",
               "TagHOD",
               "DisplayAsPrimary",
               "Values"
               ]

You can then loop over this array when accessing elements in your object, so you are always accessing them in your defined order.

In python, with an object named "data" this would look like:

 for key in keyorder:
      print data.get(key)


来源:https://stackoverflow.com/questions/62306963/oder-of-my-json-request-is-getting-sorted-in-alphabetical-order-when-i-am-gettin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!