用Python指定JSON对象中的键

2024-09-27 19:29:26 发布

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

我试图输出JSON,它有一个mac地址列表和一个与每个mac地址相关联的时间戳列表。我要查找的输出如下所示:

[
"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,但是没有键(没有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地址作为密钥?我试过很多不同的方法,但都不管用。你知道吗


Tags: injson列表forindexmac地址时间
2条回答

编辑:请参阅下面的其他评论,OP的JSON并不是有效的,但我认为问题的核心是“dictionary vs.array”问题,我已经回答了这个问题。你知道吗

看起来您正在获取数组并将它们添加到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))

(警告,未测试代码,因为我没有您的输入数据)

您期望的输出不是有效的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"
        ]
    }
]

要获取此信息,您可以执行以下操作:

list_count = 0
indices = []
mac_times_array = []
for foundMacAddress in found_mac_list:
    mac_dict = {}
    indices = [i for i, x in enumerate(macAddressesTotal) if x == foundMacAddress]
    grouped_times = []
    for index in indices:
        grouped_times.append(times[index])
    mac_dict[foundMacAddress] = grouped_times
    mac_times_array.append(mac_dict)

pprint.pprint(json.dumps(mac_times_array))

我无法确认这一点,因为我不确定输入列表found_mac_listmacAddressesTotal

相关问题 更多 >

    热门问题