你提供的字符串包含两个相连的JSON对象。在解析之前,需要将它们分开。可以通过以下步骤解析这个数据:
- 分隔JSON对象:从原始字符串中提取出两个有效的JSON对象。
- 解析每个JSON对象:使用合适的编程语言(如Python、JavaScript等)来解析这些JSON数据。
下面是用Python示例代码来实现这个过程:
import json
# 原始字符串
data = '{"device_id":"673db461ef99673c8acec2c4_home_3861","shadow":[{"service_id":"attribute","desired":{"properties":null,"event_time":null},"reported":{"properties":{"buzzer":"OFF","fan":"OFF","led":"OFF","humidity":38,"temperature":22,"light":0,"proximity":0,"co_value":871,"infrared":0},"event_time":"20241126T050051Z"},"version":3058}]}{"device_id":"673db461ef99673c8acec2c4_home_3861","shadow":[{"service_id":"attribute","desired":{"properties":null,"event_time":null},"reported":{"properties":{"buzzer":"OFF","fan":"OFF","led":"OFF","humidity":38,"temperature":22,"light":0,"proximity":0,"co_value":871,"infrared":0},"event_time":"20241126T050051Z"},"version":3058}]}'
# 将字符串分割成两个部分
json_strings = data.split('}{')
json_strings[1] = '{' + json_strings[1] # 添加缺失的开头大括号
json_strings[0] += '}' # 添加缺失的结尾大括号
# 解析每个 JSON 对象
for json_str in json_strings:
try:
parsed_json = json.loads(json_str)
# 打印 device_id
print(f"Device ID: {parsed_json['device_id']}")
# 获取 shadow 数据
shadow_array = parsed_json["shadow"]
for item in shadow_array:
reported_properties = item["reported"]["properties"]
event_time = item["reported"]["event_time"]
print(f"Reported Properties: {reported_properties}")
print(f"Event Time: {event_time}")
except json.JSONDecodeError as e:
print("JSON Decode Error:", e)
上述代码解释:
data
变量存储了你提供的 JSON 字符串。- 使用
split
方法将字符串分为两个部分,并重新添加必要的大括号,使得每一部分都形成一个有效的 JSON 对象。 - 使用
json.loads()
来解析每个 JSON 对象,提取并打印所需的信息。
输出结果:
运行上述代码时,将会输出类似以下信息:
Device ID: 673db461ef99673c8acec2c4_home_3861
Reported Properties: {'buzzer': 'OFF', 'fan': 'OFF', 'led': 'OFF', 'humidity': 38, 'temperature': 22, 'light': 0, 'proximity': 0, 'co_value': 871, 'infrared': 0}
Event Time: 20241126T050051Z
Device ID: 673db461ef99673c8acec2c4_home_3861
Reported Properties: {'buzzer': 'OFF', 'fan': 'OFF', 'led': 'OFF', 'humidity': 38, 'temperature': 22, 'light': 0, 'proximity': 0, 'co_value': 871, 'infrared': 0}
Event Time: 20241126T050051Z
这段代码能够处理你的输入数据,且能够有效地从中提取和显示所需的信息。根据实际需求,你可以进一步处理或保存这些数据。
内容由零声教学AI助手提供,问题来源于学员提问