python在for循环中解析json数据

时间:2018-03-07 11:33:41

标签: python json

我试图从json解析我的数据。 我有一个加载所有数据的函数...... 数据是这样的:

<Popup />

我想通过for循环提取设备的名称,如下所示:

devices_infos = get_devices()

    {
  "page" : 0,
  "size" : 20,
  "totalCount" : 2,
  "data" : [ {
    "namespace" : "android",
    "id" : "0000001111111",
    "creationTs" : 1516216756819,
    "name" : "Eric's phone",
    "description" : "This device was auto registered by [mqtt] ",
    "tags" : [ ],
    "properties" : { },
    "lastUpdateTs" : 1518610495832,
    "connected" : false,
    "path" : [ ],
    "metadata" : {
      "api_key_id" : "XXX000XXX000XXX",
      "connection_start_time" : "2018-02-14T12:14:04.778Z",
      "mqtt_version" : 4,
      "mqtt_username" : "json+device",
      "mqtt_timeout" : 20,
      "remote_addr" : "00.00.00.00/PORT"
    },
    "groupId" : "root",
    "groupPath" : "/"
  }, {
    "namespace" : "sensor",
    "id" : "temp001",
    "creationTs" : 1520415684605,
    "name" : "mySensor001",
    "description" : "moisture sensor",
    "tags" : [ "france", "lyon" ],
    "properties" : {
      "manufacturer" : "miel",
      "model" : "MoistureSensorV3"
    },
    "lastUpdateTs" : 1520415684605,
    "connected" : false,
    "path" : [ ],
    "groupId" : "root",
    "groupPath" : "/"
  } ]

这只会打印第一个设备,即if devices_infos is not None: print('Devices are: ') for each in devices_infos['data'][0]['name']: print (each) else: print("[!] Request failed") ,我也希望Eric's phone

2 个答案:

答案 0 :(得分:1)

删除[0]

PUT

[...]表示JSON上下文中的数组,因此您必须对其进行迭代(循环)。

答案 1 :(得分:0)

试试这个:

{{1}}

我希望这可以解决您的问题。