迭代 JSON 中的不同值并将其附加到变量中

Iterate and append the different values from JSON into a variable

我正在尝试从有效负载中迭代并附加 QIdAnswer,预期的输出类似于 12|Yes&&13|Yes&&14|Yes&&15|Yes&&16|Yes&&17|Yes&&.

我只想在保存到数据库之前连接 QIdAnswer。我怎样才能做到这一点

Qstans = str(qid)+'|'+ answer+'&&'.join([str(qid)+'|'+(answer) for ran in request.data]) 追加值的这一行

我得到的输出

12|Yes12|Yes&&12|Yes&&12|Yes&&12|Yes&&12|Yes&&12|Yes

有效负载:

0: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 150…}
1: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 151…}
2: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 152…}
3: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 153…}
4: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 154…}
5: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "Yes", QId: 155…}
6: {AuditorId: 10, Agents: "Joshi", Supervisor: "Prabhu", TicketId: "HRR6506691",Answer: "No", QId: 156…}

代码在这里:

@api_view(['POST'])
def SaveUserResponse(request):
   
  if request.method == 'POST': 

    for ran in request.data:
        qid = ran.get('QId')
        answer = ran.get('Answer')
        Qstans = str(qid)+'|'+ answer+'&&'.join([str(qid)+'|'+(answer) for ran in request.data])
        print(Qstans)

您在循环中使用了列表理解,这对于(我的理解是)您的目标来说是不必要的。在理解中,您还使用了在循环中分配的变量,导致所有 Q/A 值分别为 12 和“是”。

简单地换掉循环并使用:

if request.method == 'POST':
    Qstans = '&&'.join(str(ran.get('QId')) + '|' + str(ran.get('Answer')) for ran in request.data)

应该足够了。
我无法对此进行测试,因为您没有像评论中提到的 mozway 那样提供 Python 对象,但这应该可以进行一些小的调整(例如附加 '&&' 以防万一需要它)。

好像有两次迭代,所以你可以试试这个代码

@api_view(['POST'])
def SaveUserResponse(request):
   
  if request.method == 'POST': 
    Qstans = ""
    for ran in request.data:
        qid = ran.get('QId')
        answer = ran.get('Answer')
        Qstans = Qstans + str(qid)+'|'+ answer+'&&'
    print(Qstans)

注意 print(Qstans) 如何在循环之外