Pankaj Pankaj - 2 months ago 8
Python Question

can't print the value of json object in django

I have this json object in ajax_data variable

{
"columns[0][data]": "0",
"columns[1][name]": "",
"columns[5][searchable]": "true",
"columns[5][name]": "",
"columns[4][search][regex]": "false",
"order[0][dir]": "asc",
"length": "10",
}


I have converted it using json.loads() function like.

ajax_data = json.loads(ajax_data)


I want to get the value if "order[0][dir]" and "columns[0][data]" but if i print it using

ajax_data['order'][0]['dir]


its giving error :

KeyError at /admin/help
'order'


But same code works if i access it for length key then it works.

Answer

The keys you have used are actually not a good way of implementation.

{
    "columns[0][data]": "0", 
    "columns[1][name]": "", 
    "columns[5][searchable]": "true", 
    "columns[5][name]": "", 
    "columns[4][search][regex]": "false", 
    "order[0][dir]": "asc", 
    "length": "10", 
}

Instead of this you should hav gone for

{
    "columns": [
        {"data": "0", "name": "", "searchable": "true", "name": "", "search": {
            "regex": "false"}
        },
        {"data": "0", "name": "", "searchable": "true", "name": ""," search": {
            "regex": "false"}},
        {"data": "0", "name": "", "searchable": "true", "name": "", "search": {
            "regex": "false"}},
        {"data": "0", "name": "", "searchable": "true", "name": "", "search": {
            "regex": "false"}},
        {"data": "0", "name": "", "searchable": "true", "name": "", "search": {
            "regex": "false"}},
        {"data": "0", "name": "", "searchable": "true", "name": "", "search": {
            "regex": "false"}},
    ],
    "order": [
        {"dir": "asc"}
    ],
    "length": "10"
}

In this case ajax_data['order'][0]['dir] will result in value "asc"

For your current implementation the key is "order[0][dir]"

That is go for

ajax_data["order[0][dir]"]

Hope you understood the issue.

Structuring of json is very important when dealing with APIs. Try to restructure your json which will help for future too.