Converting JSON to Dictionary by Python [duplicate

2019-08-10 21:40发布

This question already has an answer here:

I have a dictionary like this:

{
    "reserve": {
        "duration": {
            "startTimeUnix": "",
            "startTime": "صبور باشید...",
            "endTime": "۱۳۹۴/۰۹/۰۴ ۱۲:۲۰",
            "endTimeUnix": 1448441400
        },
        "service": null,
        "reserver": {
            "first_name": "مریم",
            "last_name": "موسوی",
            "phone": "09124955173"
        }
    },
    "block": {
        "duration": null
    },
    "is_block": false,
    "taken_time": null,
    "staff": "alireza",
    "service": [
        "O5KLFPZB"
    ]
}

And then, I posted it to a Django backend server via AngularJS, then I just get <QueryDict: {}> when I use request.POST, so, I used request.body, after then I gave:

b'{
    "reserve": {
        "duration": {
            "startTimeUnix": "",
            "startTime": "\xd8\xb5\xd8\xa8\xd9\x88\xd8\xb1 \xd8\xa8\xd8\xa7\xd8\xb4\xdb\x8c\xd8\xaf...",
            "endTime": "\xdb\xb1\xdb\xb3\xdb\xb9\xdb\xb4/\xdb\xb0\xdb\xb9/\xdb\xb0\xdb\xb4        \xdb\xb1\xdb\xb2:\xdb\xb2\xdb\xb0",
            "endTimeUnix": 1448441400
        },
        "service": null,
        "reserver": {
            "first_name": "\xd9\x85\xd8\xb1\xdb\x8c\xd9\x85",
            "last_name": "\xd9\x85\xd9\x88\xd8\xb3\xd9\x88\xdb\x8c",
            "phone": "09124955173"
        }
    },
    "block": {
        "duration": null
    },
    "is_block": false,
    "taken_time": null,
    "staff": "alireza",
    "service": [
        "O5KLFPZB"
    ]
}'

pt

In views.py

import json
from django.views.decorators.csrf import csrf_exem

@csrf_exempt
def admin_block_time(request):
    dic = json.loads(request.body.encode("utf-8"))
    print(dic)

How can I convert it to Dictionary, although I tried json.loads(), but, it didn't work.

1条回答
Juvenile、少年°
2楼-- · 2019-08-10 22:05

Your input is of type bytes, therefore json.loads(your_json) will raise TypeError: the JSON object must be str, not 'bytes'.

The solution is to decode it with the encoding specified in the Content-Type HTTP Header:

>>> import json
>>> json.loads(your_json.decode("utf-8"))
{
    'is_block': False,
    'taken_time': None,
    'staff': 'alireza',
    'block': {'duration': None},
    'service': ['O5KLFPZB'],
    'reserve': {
        'service': None,
        'duration': {
            'endTime': '۱۳۹۴/۰۹/۰۴        ۱۲:۲۰',
            'startTimeUnix': '',
            'endTimeUnix': 1448441400,
            'startTime': 'صبور باشید...'
        },
        'reserver': {
            'first_name': 'مریم',
            'phone': '09124955173',
            'last_name': 'موسوی'
        }
    }
}
查看更多
登录 后发表回答