简体   繁体   中英

Python 3 iterate json return object

I have a JSON return object that I need the value from the 'id' field number for each row return.

output variable (json return object):

[{'public_key': '21A8CAEEDC0B5A0A88657C796089D9CF83BC057B', 'flags': 256, 'algorithm': 8, 'digest': 'C0B0483159C3C2B0616BC27AC12D251BF30DFBF5E2B2A6D2DE964A3BAAC68564', 'id': 28105, 'digest_type': 2, 'keytag': 57881, 'date_created': <DateTime '20150620T01:49:46' at 805f34518>}, {'public_key': '406F0435E626AD582D4A403A9AB5E52F86CC3D15', 'flags': 256, 'algorithm': 8, 'digest': 'D06634258CCD3DD7BA8F7796828A6B4DFE142F01C964D851B9FAFE3D9CC7C712', 'id': 28141, 'digest_type': 2, 'keytag': 60608, 'date_created': <DateTime '20150621T01:44:55' at 805f34630>}]

I have the JSON libraries loaded but python does not like my formatting

error:

Traceback (most recent call last):
  File "makecustdomain.py", line 262, in <module>
    json_object = json.load(output)
  File "/usr/local/lib/python3.4/json/__init__.py", line 265, in load
    return loads(fp.read(),
AttributeError: 'list' object has no attribute 'read'

code:

    domain = 'domain2.com'
    api = client.ServerProxy('https://rpc.gandi.net/xmlrpc/')
    apikey = 'privateKey'
    output = api.domain.dnssec.list(apikey, domain)
    json_object = json.load(output)
    for id in json_object[7]:
            print(id)

expected output:

28105
28141

How do I return the value for 'id' from my JSON return object?

I suspect output will always be a list ( because you're using RPC here and RPC generally serializes results into native types ) and so you'll have to do something like this:

from pprint import pprint
from operator import itemgetter

output = api.domain.dnssec.list(apikey, domain)
ids = map(itemgetter("id"), output)
pprint(ids)

Update: If the list of ids come back as ["123 456", "789"] you and you want a flattened list of ids you could do something like:

ids = list(chain(*map(str.split, map(itemgetter("id"), output))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM