JSONDecodeError:额外数据

6psbrbz9  于 2023-08-08  发布在  其他
关注(0)|答案(2)|浏览(107)

我试图将payload转换为json,但我得到了一个JSONDecodeError:额外数据错误。我需要他们是3个独立的有效载荷被张贴到一个API。
“data”:{“CustomerID”:“15263”,“时间戳”:“2023-07- 28 T17:08:23 Z”,“状态”:“networkOk”}
“data”:{“CustomerID”:“15891”,“时间戳”:“2023-07- 28 T17:08:23 Z”,“状态”:“networkOK”}
“data”:{“CustomerID”:“16986”,“时间戳”:“2023-07- 28 T17:08:23 Z”,“状态”:“networkOK”}

import json

payload= '{"CustomerID":"15263","Timestamp":"2023-07-28T15:12:48Z","Status":"networkRisk"},"1":{"CustomerID":"15891","Timestamp":"2023-07-28T15:12:48Z","Status":"networkRisk"},"2":{"CustomerID":"16986","Timestamp":"2023-07-28T15:12:48Z","Status":"networkRisk"}'

payload = json.loads(payload)

payload = json.dumps({"data":payload})

字符串

mnemlml8

mnemlml81#

将payload_JSON的结构和格式更改为字符串中的对象列表。
当使用json.loads()加载这个字符串时,它被转换为Python字典列表。接下来,在for循环中,提取列表中的每个对象,并将其作为单独的JSON有效负载发送到API服务器。

import json

# The JSON payload as an array of objects
payload_json = '[{"CustomerID":"15263","Timestamp":"2023-07-28T15:12:48Z","Status":"networkRisk"},' \
               '{"CustomerID":"15891","Timestamp":"2023-07-28T15:12:48Z","Status":"networkRisk"},' \
               '{"CustomerID":"16986","Timestamp":"2023-07-28T15:12:48Z","Status":"networkRisk"}]'

# Load the JSON data as a list of dictionaries
payload_list = json.loads(payload_json)

# Iterate through each data object and create separate payloads
for index, data in enumerate(payload_list):
    payload = json.dumps({"data": data})
    # Here, you can post the payload to the API
    print(f"Payload {index+1}: {payload}")

字符串
这是输出:

Payload 1: {"data": {"CustomerID": "15263", "Timestamp": "2023-07-28T15:12:48Z", "Status": "networkRisk"}}
Payload 2: {"data": {"CustomerID": "15891", "Timestamp": "2023-07-28T15:12:48Z", "Status": "networkRisk"}}
Payload 3: {"data": {"CustomerID": "16986", "Timestamp": "2023-07-28T15:12:48Z", "Status": "networkRisk"}}

zbwhf8kr

zbwhf8kr2#

您可以使用此示例将字符串“拆分”为3个字典。但我建议修复字符串的制作方式(使其正确的Json):

import json

payload = '{"CustomerID":"15263","Timestamp":"2023-07-28T15:12:48Z","Status":"networkRisk"},"1":{"CustomerID":"15891","Timestamp":"2023-07-28T15:12:48Z","Status":"networkRisk"},"2":{"CustomerID":"16986","Timestamp":"2023-07-28T15:12:48Z","Status":"networkRisk"}'

# "quick-and-dirty" way to make json.loads work
payload = json.loads('{"0":' + payload + "}")

for v in payload.values():
    print(v)

字符串
印刷品:

{'CustomerID': '15263', 'Timestamp': '2023-07-28T15:12:48Z', 'Status': 'networkRisk'}
{'CustomerID': '15891', 'Timestamp': '2023-07-28T15:12:48Z', 'Status': 'networkRisk'}
{'CustomerID': '16986', 'Timestamp': '2023-07-28T15:12:48Z', 'Status': 'networkRisk'}

相关问题