将JSON转换为数组?

时间:2014-12-09 18:15:25

标签: python json

我想将代理列表的JSON数据转换为python中的数组。我的JSON是一个例子。我想获得列表对象下的所有主机的数组。

我不确定是否应该(或可以)遍历列表中的每个主机并将其提取到数组中?或者如果有更好/更清洁的方式。

编辑:抱歉,我应该评论说我正在通过请求读取该文件。看来我的JSON已经正确解码了,我试图对已经解码的JSON做json.loads。

{
  "status": "",
  "list": [
    {
      "host": "118.26.147.119:80",
      "ip_address": "118.26.147.119",
      "port": 80,
      "country_code": "CN",
      "uptime": 86.2,
      "connectionTime": 1.2633587,
      "type": "http",
      "lastValidatedDate": "2014-12-09T15:06:26",
      "lastValidatedStatus": true,
      "anonymity": false,
      "supports_google": false,
      "supports_browsing": true
    },
    {
      "host": "111.13.109.52:80",
      "ip_address": "111.13.109.52",
      "port": 80,
      "country_code": "CN",
      "uptime": 99.9,
      "connectionTime": 1.4086116,
      "type": "http",
      "lastValidatedDate": "2014-12-09T14:49:31",
      "lastValidatedStatus": true,
      "anonymity": false,
      "supports_google": false,
      "supports_browsing": true
    }
  ]
}

1 个答案:

答案 0 :(得分:1)

Python附带了一个用于读取JSON的模块。如果您这样做:

import json
jdict = json.decoder.JSONDecoder().decode('''{
  "status": "",
  "list": [
    {
      "host": "118.26.147.119:80",
      "ip_address": "118.26.147.119",
      "port": 80,
      "country_code": "CN",
      "uptime": 86.2,
      "connectionTime": 1.2633587,
      "type": "http",
      "lastValidatedDate": "2014-12-09T15:06:26",
      "lastValidatedStatus": true,
      "anonymity": false,
      "supports_google": false,
      "supports_browsing": true
    },
    {
      "host": "111.13.109.52:80",
      "ip_address": "111.13.109.52",
      "port": 80,
      "country_code": "CN",
      "uptime": 99.9,
      "connectionTime": 1.4086116,
      "type": "http",
      "lastValidatedDate": "2014-12-09T14:49:31",
      "lastValidatedStatus": true,
      "anonymity": false,
      "supports_google": false,
      "supports_browsing": true
    }
  ]
}''')

然后jdict将包含一个表示JSON内容的字典,您可以使用该字典访问该字典。

hosts = jdict['list']