简体   繁体   中英

Using Json.load Changes The Order Of My Config File

I have been trying to find a solution to this issue and I have not been able to. I have created a UI which runs using a .config file. My code retrieves all the necessary information without issues and everything runs smoothly. Currently using this method to read the file since this is what works best for my occasion:

    with open(config_file_path_name, 'r') as i:
        self.contents_dict = json.load(i)

My problem is the following, I not only use the UI to look through the file and get info but also to adjust values and then write them back to the file at the end. I would have no problem if I never looked into the.config file again but I most definitely have to whenever I would like to add a new field in there (my UI automatically generates any new fields according to the file). Due to this process, I have formatted the .config file manually to have things in a specific order so I can easily find my way around when adding things (and to make it look more organized). Problem is when the file goes through the json.load , since dictionaries don't need to have a specific order, the file comes out completely rearranged. Not sure why it was designed this way but I cannot find a way to keep the original order of the file.

Example:

Let's say the file is set up manually like this:

    {
      'C' : '3',
      'A' : '1',
      'B' : '2', 
    }

The function json.load would immediately change it to something different like this as it reads it:

    {
      'B' : '2',
      'C' : '3',
      'A' : '1', 
    }

Taking a look here I saw people talking about the OrderedDict function but that does not work for me since I want the order I set up before, not the one created by this function. At first I thought it was related to previously using ast.literal_eval due to the way the file was formatted but after spending some time changing some things and switching to json.load I realized that was not the issue. Any suggestion would be greatly appreciated.

Thank you for your time!

I have been able to resolve the issue!

Utilizing the object_pairs_hook=collections.OrderedDict does work when opening the file but for some reason it throws a sleeper error when fully written like above. Instead I had to do from collections import OrderedDict which then allows me to do object_pairs_hook=OrderedDict . My PyCharm still throws the Optional[(List[Tuple[Any, Any]]) -> Any]', got 'Type[OrderedDict] highlight but when I run the code it does what it should.

Thank you for your time!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM