【问题标题】:How to convert bytes to json in python如何在python中将字节转换为json
【发布时间】:2021-09-09 09:04:30
【问题描述】:

我正在尝试将字节数据转换为 JSON 数据。我在转换数据时遇到错误。

a = b'orderId=570d3e38-d6486056e&orderAmount=10.00&referenceId=34344&txStatus=SUCCESS&txMsg=Transaction+Successful&txTime=2021-06-26+12%3A03%3A12&signature=njtH5Dzmg6RJ1KB'

我用这个来转换

json.loads(a.decode('utf-8'))

我想得到这样的回应

orderAmount = 10.00
orderId = 570d3e38-d6486056e
txStatus = SUCCESS

【问题讨论】:

  • 您似乎只是想将 查询字符串 转换为字典?你是在哪里拿到的?通常,传递给 Django 的查询字符串可以作为 QueryDict 访问,request.GET 可以访问该字符串

标签: json python-3.x django


【解决方案1】:

您在这里看到的是query string [wiki],您可以通过以下方式读取查询字符串:

from django.http import QueryDict

a = b'orderId=570d3e38-d6486056e&orderAmount=10.00&referenceId=34344&txStatus=SUCCESS&txMsg=Transaction+Successful&txTime=2021-06-26+12%3A03%3A12&signature=njtH5Dzmg6RJ1KB'

b = QueryDict(a)

使用给定的样本数据,我们有一个QueryDict [Django-doc],看起来像:

>>> b
<QueryDict: {'orderId': ['570d3e38-d6486056e'], 'orderAmount': ['10.00'], 'referenceId': ['34344'], 'txStatus': ['SUCCESS'], 'txMsg': ['Transaction Successful'], 'txTime': ['2021-06-26 12:03:12'], 'signature': ['njtH5Dzmg6RJ1KB']}>

如果你下标,那么你总是得到最后一项,所以:

>>> b['orderId']
'570d3e38-d6486056e'
>>> b['orderAmount']
'10.00'
>>> b['orderId']
'570d3e38-d6486056e'
>>> b['txStatus']
'SUCCESS'

如果您使用视图,您还可以通过以下方式找到 URL 的查询字典:

def my_view(request):
    b = request.GET
    # …

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-24
    • 2012-02-07
    • 2015-04-06
    • 1970-01-01
    • 2018-05-24
    • 2021-04-24
    • 1970-01-01
    • 2017-08-11
    相关资源
    最近更新 更多