Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #112035 > unrolled thread

JSON result parsing

Started byTUA <kai.peters@gmail.com>
First post2016-07-29 16:45 -0700
Last post2016-07-30 17:20 +0100
Articles 3 — 3 participants

Back to article view | Back to comp.lang.python


Contents

  JSON result parsing TUA <kai.peters@gmail.com> - 2016-07-29 16:45 -0700
    Re: JSON result parsing John Gordon <gordon@panix.com> - 2016-07-30 03:25 +0000
    Re: JSON result parsing Ben Bacarisse <ben.usenet@bsb.me.uk> - 2016-07-30 17:20 +0100

#112035 — JSON result parsing

FromTUA <kai.peters@gmail.com>
Date2016-07-29 16:45 -0700
SubjectJSON result parsing
Message-ID<fd02ca3a-47af-4a0b-b309-56bc732ea071@googlegroups.com>
Calls to my REST api may either return a dict (for single results) or a list of dicts (for multiple results).

I receive these results using the requests library.

I want to retrieve the value for a key 'ID' but only if I have a single result and, obviously, if ID is present.

How can I do this with pythonic elegance?

Thanks for all suggestions!

[toc] | [next] | [standalone]


#112039

FromJohn Gordon <gordon@panix.com>
Date2016-07-30 03:25 +0000
Message-ID<nnh6mu$k0i$1@reader2.panix.com>
In reply to#112035
In <fd02ca3a-47af-4a0b-b309-56bc732ea071@googlegroups.com> TUA <kai.peters@gmail.com> writes:

> I want to retrieve the value for a key 'ID' but only if I have a single result and, obviously, if ID is present.

> How can I do this with pythonic elegance?

> Thanks for all suggestions!

    if len(results) == 1 and 'ID' in results:
        return results['ID']

    else:
        return 'something else'

-- 
John Gordon                   A is for Amy, who fell down the stairs
gordon@panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"

[toc] | [prev] | [next] | [standalone]


#112085

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2016-07-30 17:20 +0100
Message-ID<87wpk3w11m.fsf@bsb.me.uk>
In reply to#112035
TUA <kai.peters@gmail.com> writes:

> Calls to my REST api may either return a dict (for single results) or
> a list of dicts (for multiple results).

I think John's answer missed this part.

> I receive these results using the requests library.
>
> I want to retrieve the value for a key 'ID' but only if I have a
> single result and, obviously, if ID is present.

If r is the result of the request, just testing

  if 'ID' in r: ... whatever ...

would do.  The result will be False if r is a list or the single result
does not have an ID.

> How can I do this with pythonic elegance?

Ah, that I leave to others.

-- 
Ben.

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web