Home > Software design >  How to get original JSON format order after updating new key value?
How to get original JSON format order after updating new key value?

Time:11-25

I updated a new JSON key value in the JSON value, but when I write the order of the JSON file is changed, so how do I get my original order with the new update key value?

Original JSON format:

value = [
    {
      "result": [
                        {
                              "allow": "notes",
                              "url": "https://google.com",
                              "np_url": "https://www.google.com/downloads/",
                              "rank": "2"
                              "info": "ok"
                        },
                        {
                              "allow": "notes2",
                              "url": "https://www.yahoo.com",
                              "np_url": "https://imp.com/download",
                              "rank": "7",
                              "info": "cancel"
                         },
                    ]
    }
]

When I add new key and value the order changes when I write a JSON.

Print value shows original, but when I write and use sort_keys = True and without sort_keys = True it also gets different JSON format order

Code:

if
  ....
  kk['art'] = pencil
else
  ...
  kk['art'] = pencil

print(value)

import json
with open("example.json", "w", encoding='utf-8') as f:
    json.dump(value, f, ensure_ascii=False,indent=4, sort_keys=True)

output:

value = [
    {
      "result": [
                        {
                              "allow": "notes",
                              "art": "pencil",
                              "url": "https://google.com",
                              "info": "ok"
                              "np_url": "https://www.google.com/downloads/",
                              "rank": "2"
                        },
                        {
                              "allow": "notes2",
                              "art": "pen",
                              "url": "https://www.yahoo.com",
                              "info": "cancel"
                              "np_url": "https://imp.com/download",
                              "rank": "7",
                         },
                    ]
    }
]

expected Output:

value = [
    {
      "result": [
                        {
                              "allow": "notes",
                              "art": "pencil",
                              "url": "https://google.com",
                              "np_url": "https://www.google.com/downloads/",
                              "rank": "2"
                              "info": "ok"
                        },
                        {
                              "allow": "notes2",
                              "art": "pen",
                              "url": "https://www.yahoo.com",
                              "np_url": "https://imp.com/download",
                              "rank": "7",
                              "info": "cancel"
                         },
                    ]
    }
]

CodePudding user response:

If you need to set the order of the items in a dictionary for some reason, you must do so adding items in your chosen key order. Python preserves key insertion order as a language feature (3.7 ).

I can think of a few ways that you might do this, for example creating a template dictionary with None values and cloning it to create individual items in your result list.

I think though I would recommend that you do whatever data manipulation you want and then iterate the result list and for each item in the list, rebuild it with an expected key ordering.

This seems straightforward enough to start.

value = [
    {
        "result": [
            {
                "allow": "notes",
                "art": "pencil",
                "url": "https://google.com",
                "info": "ok",
                "np_url": "https://www.google.com/downloads/",
                "rank": "2"
            },
            {
                "allow": "notes2",
                "art": "pen",
                "url": "https://www.yahoo.com",
                "info": "cancel",
                "np_url": "https://imp.com/download",
                "rank": "7",
            },
        ]
    }
]

def set_key_order(my_dict):
    key_order = ["allow", "art", "url", "np_url", "rank", "info"]
    return {key: my_dict[key] for key in key_order if key in my_dict.keys()}

value[0]["result"] = [set_key_order(x) for x in value[0]["result"]]

print(value)

This will give you a result that looks like:

[
    {
        'result': [
            {
                'allow': 'notes',
                'art': 'pencil',
                'url': 'https://google.com',
                'np_url': 'https://www.google.com/downloads/',
                'rank': '2',
                'info': 'ok'
            },
            {
                'allow': 'notes2',
                'art': 'pen',
                'url': 'https://www.yahoo.com',
                'np_url': 'https://imp.com/download',
                'rank': '7',
                'info': 'cancel'
            }
        ]
    }
]
  • Related