如何从嵌套的json值中提取parrticular值。

时间:2015-12-08 03:16:06

标签: python json django mongodb

我是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"
    }
  ]
}

我用来从对象中获取价值的代码

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, in <module>
    parsed = 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。

感谢。

2 个答案:

答案 0 :(得分:5)

您正在将请求对象而不是str对象传递给json.loads()。你需要改变

parsed = json.loads(r)

parsed = json.loads(r.text)

此外,parsed['objects']是一个列表,您需要访问其第一个元素&amp;然后获取密钥ip

>>> print(parsed['objects'][0]['ip'])

答案 1 :(得分:2)

问题出在这一行:parsed = json.loads(r)

你正在回复json的回复,但却忘了将json个元素投放到json.loads,而是让它<Response [200]>

    >>> r = requests.get('http://www.google.com')
    >>> r
    <Response [200]>
    >>> type(r)
    <class 'requests.models.Response'>

(仔细查看错误消息。Expected string or buffer这意味着您提供了 NOT 字符串或缓冲区(在这种情况下为对象) ))
 这就是str(r)无效的原因。因为它只是将<Response 200>转换为'<Response 200>',这显然不是json。


将此行更改为parsed = json.loads(r.text)

   >>> type(r.text)
   <type 'unicode'>

然后parsed['objects'][0]['ip']应该给你IP地址:) 您可以找到有关请求模块here

的更多信息