python - 使用 Python 指定 JSON 对象中的键

标签 python json

我正在尝试输出包含 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/

相关文章:

json - 在 VBA 中返回空 JSON 引发类型不匹配错误

ios - 如何在 prepareForSegue 方法中访问对象数组中选定对象的不同属性或特性

javascript - 任何人都可以指导我使用 js 或 python 组合可视化吗?

python - 为什么我们在django的model_name.object.get_or_create()中的get_or_create之后写[0]

用于将 Windows 路径更改为 Unix 路径的 Python 脚本

php - 创建 "two way"配置文件

python - 将嵌套的 JSON 数据传递为 Html 表格式

javascript - 如何在不使用ajax的情况下发送POST请求

Python - 如何删除选定列表框项目周围的边框?

python - Hadoop获得了Expected JSON。是否启用了WebHDFS?得到了 ''