将JSON转换为数组? [英] Convert JSON to Array?
问题描述
我想将代理列表的JSON数据转换为python中的数组.下面是我的JSON示例.我想获取列表对象下所有主机的数组.
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.
对不起,应该评论我正在通过请求读取该文件.看来我的JSON已经正确解码,并且我尝试对已经解码的JSON执行json.loads.
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的模块.如果您执行以下操作:
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
}
]
}''')
然后jdict
将包含一个表示JSON内容的字典,您可以使用例如
Then jdict
will contain a dictionary representing the contents of the JSON, which you can access with e.g.
hosts = jdict['list']
这篇关于将JSON转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!