我从python脚本创建了json,这是我为获取json数据而编写的代码:
import requests
import json
import ConfigParser
url = "xxx"
payload = "items.find({ \"repo\": {\"$match\" : \"nswps-*\"}}).include(\"name\",\"repo\",\"path\")\r\n"
headers = {
'Content-Type': "text/plain",
'Authorization': "Basic xxxxxxxxx",
'Accept': "*/*",
'Cache-Control': "no-cache",
'Host': "xxxxxx.com",
'accept-encoding': "gzip, deflate",
'content-length': "77",
'Connection': "keep-alive",
'cache-control': "no-cache"
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
上面的代码给了我json文件,它是一个包含多个对象的巨大文件。由于人工制品的某些限制,我无法获得以nswps开头的存储库,但结果是所有存储库名称。 json文件具有如下数据:
"repo" : "npm-remote-cache",
"path" : "zrender/-",
"name" : "zrender-4.0.7.tgz"
},{
"repo" : "npm-remote-cache",
"path" : "ztree/-",
"name" : "ztree-3.5.24.tgz"
},{
"repo" : "nswps-docker-inprogress-local",
"path" : "ace/core/latest",
"name" : "manifest.json"
},{
"repo" : "nswps-docker-inprogress-local",
"path" : "ace/core/latest",
"name" : "sha256__0a381222a179dbaef7d1f50914549a84e922162a772ca5346b5f6147d0e5aab4"
},{
.........
现在,我需要创建一个python脚本,以提取其中仅具有nswps值的对象的对象,从上述json可以说,我需要这样的数据:
{
"repo" : "nswps-docker-inprogress-local",
"path" : "ace/core/latest",
"name" : "manifest.json"
},{
"repo" : "nswps-docker-inprogress-local",
"path" : "ace/core/latest",
"name" : "sha256__0a381222a179dbaef7d1f50914549a84e922162a772ca5346b5f6147d0e5aab4"
}
答案 0 :(得分:1)
我可以在@furas的帮助下成功完成此操作,再次感谢! 解决方案代码如下:
response = requests.request("POST", url, data=payload, headers=headers)
list = response.text
data = response.json()['results']
print("Line#24")
output_dict = [items for items in data if 'nswps' in items['repo']]
答案 1 :(得分:0)
使用
data = response.json()
您应该将JSON
转换为Python的列表
假设您有data
data = [
{"repo" : "npm-remote-cache",
"path" : "zrender/-",
"name" : "zrender-4.0.7.tgz"
},{
"repo" : "npm-remote-cache",
"path" : "ztree/-",
"name" : "ztree-3.5.24.tgz"
},{
"repo" : "nswps-docker-inprogress-local",
"path" : "ace/core/latest",
"name" : "manifest.json"
},{
"repo" : "nswps-docker-inprogress-local",
"path" : "ace/core/latest",
"name" : "sha256__0a381222a179dbaef7d1f50914549a84e922162a772ca5346b5f6147d0e5aab4"
}
]
然后您可以使用for
循环检查列表中的每个项目并仅选择其中一些
for item in data:
if item['repo'].startswith('nswps'):
print(item)
并作为列表理解
selected = [item for item in data if item['repo'].startswith('nswps')]