Python: JSON string to list of dictionaries - Getting error when iterating

前端 未结 3 2034
暖寄归人
暖寄归人 2021-02-01 20:49

I am sending a JSON string from Objective-C to Python. Then I want to break contents of the string into a Python list. I am trying to iterate over a string (any string for now):

相关标签:
3条回答
  • 2021-02-01 20:59

    for python 3.6 above, there has a little difference

    s = '[{"i":"imap.gmail.com","p":"someP@ss"},{"i":"imap.aol.com","p":"anoterPass"}]'
    jdata = json.loads(s)
    print (jdata)
    for d in jdata:
        for key, value in d.items():
            print (key, value)
    
    
    [{'i': 'imap.gmail.com', 'p': 'someP@ss'}, {'i': 'imap.aol.com', 'p': 'anoterPass'}]
    i imap.gmail.com
    p someP@ss
    i imap.aol.com
    p anoterPass
    
    0 讨论(0)
  • 2021-02-01 21:00

    json.loads(s) will return you list. To iterate over it you don't need iteritems.

    >>> jdata = json.loads(s)
    >>> for doc in jdata:
    ...     for key, value in doc.iteritems():
    ...          print key, value
    
    0 讨论(0)
  • 2021-02-01 21:04

    Your JSON data is a list of dictionaries, so after json.loads(s) you will have jdata as a list, not a dictionary.

    Try something like the following:

    import json
    
    s = '[{"i":"imap.gmail.com","p":"someP@ss"},{"i":"imap.aol.com","p":"anoterPass"}]'
    jdata = json.loads(s)
    for d in jdata:
        for key, value in d.iteritems():
            print key, value
    
    0 讨论(0)
提交回复
热议问题