我正在尝试输出包含 mac 地址列表和与每个 mac 地址关联的时间戳列表的 JSON。我正在寻找的输出看起来像这样:
[
"B2:C7:23:10:A0":
[
"2014-04-04T21:30:46.348900800Z",
"2014-04-04T21:30:46.348900800Z",
"2014-04-04T21:30:46.348900800Z",
"2014-04-04T21:14:34.305303100Z",
"2014-04-04T21:14:34.285302000Z",
"2014-04-04T21:14:33.905280300Z"
],
"C7:99:12:F2:00":
[
"2014-04-09T22:18:43.162844700Z",
"2014-04-09T22:02:39.138705700Z",
"2014-04-09T22:02:37.429608000Z",
"2014-04-09T22:02:36.966581500Z",
"2014-04-09T22:02:36.966581500Z",
"2014-04-09T22:02:36.966581500Z",
],
]
现在,我的代码生成了上面的 json,但没有 key (没有 mac 地址),只有时间戳组。
list_count = 0
indices = []
mac_times_array = []
for foundMacAddress in found_mac_list:
indices = [i for i, x in enumerate(macAddressesTotal) if x == foundMacAddress]
grouped_times = []
for index in indices:
grouped_times.append(times[index])
mac_times_array.append(grouped_times)
stacked_array = [i for i in mac_times_array]
pprint.pprint(json.dumps(stacked_array))
所以我的问题是,如何将 mac 地址添加为 key ?我尝试了很多不同的方法,但没有任何效果。
最佳答案
编辑:请参阅下面的其他评论,OP 的 JSON 原样无效,但我认为问题的实质是处理“字典与数组”问题,我已经回答了。
看起来您正在获取数组并将它们添加到 mac_times_array
。您应该改为使用字典,并将 foundMacAddress 设为键。做这样的事情:
list_count = 0
indices = []
mac_times_dict = {}
for foundMacAddress in found_mac_list:
indices = [i for i, x in enumerate(macAddressesTotal) if x == foundMacAddress]
grouped_times = []
for index in indices:
grouped_times.append(times[index])
mac_times_dict[foundMacAddress] = grouped_times
# stacked_array = [i for i in mac_times_array]
pprint.pprint(json.dumps(mac_times_dict))
(警告,代码未测试,因为我没有您的输入数据)
关于python - 使用 Python 指定 JSON 对象中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23019488/