我是python的新手。
我的要求不高(即)只想从JSON格式中提取一个值。
如果我错了,请纠正我。
JSON输入为:
{ "meta": { "limit": 1, "next": "/api/v1/ips/?username=sic1&api_key=689db0740ed73c2bf6402a7de0fcf2d7b57111ca&limit=1&objects=&offset=1", "offset": 0, "previous": null, "total_count": 56714 }, "objects": [ { "_id": "556f4c81dcddec0c41463529", "bucket_list": [], "campaign": [ { "analyst": "prabhu", "confidence": "medium", "date": "2015-06-03 14:50:41.440000", "name": "Combine" } ], "created": "2015-06-03 14:50:41.436000", "ip": "85.26.162.70", "locations": [], "modified": "2015-06-18 09:50:51.612000", "objects": [], "relationships": [ { "analyst": "prabhu", "date": "2015-06-18 09:50:51.369000", "rel_confidence": "unknown", "rel_reason": "N/A", "relationship": "Related_To", "relationship_date": "2015-06-18 09:50:51.369000", "type": "Indicator", "value": "556f4c81dcddec0c4146353a" } ], "releasability": [], "schema_version": 3, "screenshots": [], "sectors": [], "source": [ { "instances": [ { "analyst": "prabhu", "date": "2015-06-03 14:50:41.438000", "method": "trawl", "reference": "http://www.openbl.org/lists/base_30days.txt" } ], "name": "www.openbl.org" } ], "status": "New", "tickets": [], "type": "Address - ipv4-addr" } ] }
我用于从对象获取仅IP价值的代码
import requests from pprint import pprint import json url = 'http://127.0.0.1:8080/api/v1/ips/' params = {'api_key':'xxxxxx','username': 'abcd'} r = requests.get(url, params=params, verify=False) parsed = json.loads(r) print (parsed['objects']['ip'])
我收到的错误是:
Traceback (most recent call last): File "testapi.py", line 9, inparsed = json.loads(r) File "/usr/lib/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer
我只想从JSON输入中获取IP。
谢谢。
您正在将请求对象而不是str
对象传递给json.loads()
。你需要改变
parsed = json.loads(r)
至
parsed = json.loads(r.text)
另外,parsed['objects']
是一个列表,您需要访问它的第一个元素,然后获取键ip
:
>>> print(parsed['objects'][0]['ip'])