如何在http触发器函数的响应中循环遍历JSON文件的JSON对象?

2024-10-04 03:26:49 发布

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

我试图解析JSON数组并返回它们

我发现我可以在Python的HttpTrigger函数之外使用类似的东西

response['Body'] = [json.loads(item['Body']['bytes']) for item in response]

我想在我的HTTP触发器函数中这样做

我想象的是这样的:

with open('json_file.json','rb') as file:
               jsonStr = file.read()
               
return func.HttpResponse(json.loads(jsonStr)['Body']['bytes'] for jsonStr item in func.HttpResponse, status_code=200)

其中json_file.json是包含以下内容的文件

json_file.json

[
  {"id":1,"receiver":"77777777","message":{"test":" test signal","VehId":3,"DriverId":2,"GUID":"1s3q1d-s546dq1-8e22e","LineId":2,"SvcId":2,"Lat":-64.546547,"Lon":-68.546547,"TimeStamp":"2021-03-18T08:29:36.758Z","Recorder":"dq65ds4qdezzer","Env":"PRD"},"operator":20404,"sender":"MSISDN","binary":1,"sent":"2021-03-29T08:29:36.758Z"},
  {"id":1,"receiver":"77777777","message":{"test":" test signal","VehId":3,"DriverId":2,"GUID":"1s3q1d-s546dq1-8e22e","LineId":2,"SvcId":2,"Lat":-64.546547,"Lon":-68.546547,"TimeStamp":"2021-03-18T08:29:36.758Z","Recorder":"dq65ds4qdezzer","Env":"PRD"},"operator":20404,"sender":"MSISDN","binary":1,"sent":"2021-03-29T08:29:36.758Z"},
  {"id":1,"receiver":"77777777","message":{"test":" test signal","VehId":3,"DriverId":2,"GUID":"1s3q1d-s546dq1-8e22e","LineId":2,"SvcId":2,"Lat":-64.546547,"Lon":-68.546547,"TimeStamp":"2021-03-18T08:29:36.758Z","Recorder":"dq65ds4qdezzer","Env":"PRD"},"operator":20404,"sender":"MSISDN","binary":1,"sent":"2021-03-29T08:29:36.758Z"}
]

我知道返回不能与“func.HttpResponse”一起使用,但我不知道如何使用Python中的HTTP触发器函数循环遍历文件中的所有JSON对象

问候


Tags: 函数testidjsonmessagesignalbodyitem
1条回答
网友
1楼 · 发布于 2024-10-04 03:26:49
import json
with open('json_file.json','rb') as file:
               test = file.readlines()
num_lines = sum(1 for line in open('json_file.json'))
jsonarr = []
print(num_lines)
for x in range(1,num_lines-1):
    if x!=3:
        #print(test[x].decode('utf8')[:-3])
        data = json.loads(test[x].decode('utf8')[:-3])
        jsonarr.append(data)
    else:
        #print(test[x].decode('utf8'))
        data = json.loads(test[x].decode('utf8'))
        jsonarr.append(data)

for json in jsonarr:
    item = json["id"]
    print(item)

相关问题 更多 >