简体   繁体   中英

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.

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.

That's because length is a key in that json object, and order is not. The key names are the entire strings inside the quotes: columns[0][data] , order[0][dir] , etc.

Those are unusual key names, but perfectly valid.

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