TypeError:字符串索引在djang中必须是整数

2024-09-30 01:31:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将json存储到bigchainDB中。但问题是,当我硬编码json对象并在其他节点间广播时,它会成功。但是当我从邮递员那里发送相同的json对象时,我收到一个错误string indices must be integers

这是我的功能

 def index(request):
    root = settings.BIGCHAINDB
    bdb = BigchainDB(root)
    alice, bob = generate_keypair(), generate_keypair()
    insertDB =  json.dumps(request.body.decode("utf-8"))
    jsonDict =  json.loads(insertDB)
    prepared_token_tx = bdb.transactions.prepare(
        operation='CREATE',
        signers=alice.public_key,
        recipients=[([bob.public_key], 10)],
        asset=jsonDict)
    fulfilled_token_tx = bdb.transactions.fulfill(
        prepared_token_tx,
        private_keys=alice.private_key)
    bdb.transactions.send_commit(fulfilled_token_tx)
    txid = fulfilled_token_tx['id']
    return HttpResponse(txid)

JSON对象:

{"data" : { "cphNumber": "321", "farmName": "313", "addressLine1": "13", "addressLine2": "13", "region": "13", "postalCode": "13", "corrName": "13", "corrAddressLine1": "131", "corrAddressLine2": "31", "corrRegion": "31", "corrCountry": "321", "corrPostal": "31", "corrMobile": "321", "corrEmail": "31", "agentName": "31", "agentAddressLine1": "313", "agentAddressLine2": "132", "agentRegion": "13", "agentCountry": "132", "agentPostal": "132", "brn": "13", "animalSpecies": "132" } }

任何建议都是非常欢迎的。提前谢谢。在


Tags: 对象keytokenjsonrequestrootgeneratebob
1条回答
网友
1楼 · 发布于 2024-09-30 01:31:14

这里的问题是您在request.body上使用json.dumps(),它已经是一个字符串。因此,当您使用json.loads()时,您的数据不会被解析为dict。在

 def index(request):
    root = settings.BIGCHAINDB
    bdb = BigchainDB(root)
    alice, bob = generate_keypair(), generate_keypair()
    insertDB =  request.body.decode("utf-8")  # Don't use json.dumps() here
    jsonDict =  json.loads(insertDB)
    prepared_token_tx = bdb.transactions.prepare(
        operation='CREATE',
        signers=alice.public_key,
        recipients=[([bob.public_key], 10)],
        asset=jsonDict)
    fulfilled_token_tx = bdb.transactions.fulfill(
        prepared_token_tx,
        private_keys=alice.private_key)
    bdb.transactions.send_commit(fulfilled_token_tx)
    txid = fulfilled_token_tx['id']
    return HttpResponse(txid)

docs

相关问题 更多 >

    热门问题