【发布时间】:2018-06-19 18:58:30
【问题描述】:
我正在从一个 json 端点提取数据,该端点返回一个列表。
这个列表中的一些元素,我想扔掉。我只对某些元素感兴趣。
我是这样提取数据的:
# Pull the data
url = "https://my-endpoint.com"
user = 'user1'
pwd = 'password1'
response = requests.get(url, auth=(user, pwd))
data = json.loads(response.text)
有效载荷类似于:
[{
"apples": {
"value": 0.0
},
"oranges": {
"value": 0.0
},
"name": "testing123"
},
{
"apples": {
"value": 0.0
},
"oranges": {
"value": 0.0
},
"name": "foobar"
},
{
"apples": {
"value": 0.0
},
"oranges": {
"value": 0.0
},
"name": "testing456"
}]
假设上面继续使用许多其他元素,但名称不同。如何提取所有数据,但排除我想要的?
从上面的示例中,我想提取名称“testing123”和“testing456”的所有数据,但排除“foobar”中的数据。
我将迭代新列表以提取我需要的数据。
【问题讨论】:
-
有效负载已损坏,请发布一个有效的。
-
构建一个只包含您想要的项目的列表理解:
[item for item in data if item['name'] in ('testing123', 'testing456')] -
抱歉,我已经更新了 json 有效负载。
标签: python json loops python-requests