Convert JSON to Array?

2020-05-09 22:06发布

I want to convert JSON data for a proxy list to an array in python. My JSON is below for an example. I want to get an array of all the hosts under the list object.

I'm not sure if I should (or can) loop through each host in the list and just extract it into an array? or if there is a better/cleaner way.

Edit: Sorry, should have commented that I was reading that file in through requests. It appears my JSON was already decoded properly and I tried to do json.loads against the already decoded JSON.

{
  "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
    }
  ]
}

标签: python json
1条回答
爷、活的狠高调
2楼-- · 2020-05-09 23:01

Python ships with a module for reading JSON. If you do something like this:

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
    }
  ]
}''')

Then jdict will contain a dictionary representing the contents of the JSON, which you can access with e.g.

hosts = jdict['list']
查看更多
登录 后发表回答