【问题标题】:How can I get the length of an array in a nested JSON object returned by Python requests?如何获取 Python 请求返回的嵌套 JSON 对象中数组的长度?
【发布时间】:2017-08-12 08:47:49
【问题描述】:

我正在尝试将一些代码从 Perl 移植到 Python。该代码使用非默认标头执行 HTTP GET 请求。响应是一个 JSON 文档。顶级元素是具有名为queryResponse 的键的对象。该元素的值也是一个对象,它有一个名为entity 的键。该元素的值是一个数组。我想要那个数组中元素的数量。

这是 Perl 代码:

my ($first, $max, $count) = (0, 1000, 1000);

while ($count == $max) {
  my $debugFlag = 1;
  my $uri = "/webacs/api/v2/data/Devices.json?.full=true&.nocount=true&" .
            ".firstResult=$first&.maxResults=$max";
  $piConnection->GET($uri, $headers);
  my $response = decode_json $piConnection->responseContent();
  $first = $first + 1000;
  $count = scalar @{$response->{queryResponse}{entity}};

这是我目前在 Python 中所拥有的:

firstResult = 0
maxResults = 1000
count = 1000

while count == maxResults:
    test_urn = (URL + '/webacs/api/v2/data/Devices?.full=True&.nocount=True&.maxResults=%d&.firstResult=%d') % (maxResults, firstResult)
    get_response = requests.get(test_urn, verify=False)
    firstResult = firstResult + 1000
    count = len(get_response['queryResponse']) # This is the line I need help with
    print get_response.text

我遇到问题的部分是在 JSON 响应中获取数组的长度。我该怎么做?

【问题讨论】:

  • 两条建议让您获得更多回复:(1) 发布工作代码,以便我们重现您的部分结果并测试我们的解决方案(这包括定义变量,URL) ; (2) 描述你想要的功能,以便非 Perl 程序员可以提供帮助。

标签: python python-2.7 python-requests


【解决方案1】:
use JSON::XS qw( decode_json );
my $response_json = '{ "queryResponse": { "entity": [ "a", "b", "c" ] } }';
my $response = decode_json($response_json);
my $count = @{ $response->{queryResponse}{entity} };

等价于

import json
response_json = '{ "queryResponse": { "entity": [ "a", "b", "c" ] } }'
response = json.loads(response_json)
count = len(response['queryResponse']['entity'])

除了错误的处理方式。


response_json是从get_response.text获取的。
response可以从get_response.json()获取或者如图所示。

【讨论】:

  • 并且 requests 有一个 shortcut 用于解码 JSON 响应,所以 OP 可以只做 response = requests.get(...) 后跟 count = len(response.json()['queryResponse']['entity'])
  • 我收到以下错误: Traceback(最近一次调用最后一次):文件“primeapi.py”,第 48 行,在 count = len(get_response['queryResponse']['entity TypeError : 'Response' 对象不可订阅
  • 就像我说的,错误的处理方式可能会有所不同。既然你是 python 程序员,这是我第二个 python 程序,我会让你处理。
猜你喜欢
  • 1970-01-01
  • 2015-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
  • 2020-09-08
  • 1970-01-01
相关资源
最近更新 更多