Check if key exists and iterate the JSON array using Python

前端 未结 7 582
南旧
南旧 2020-12-02 06:28

I have a bunch of JSON data from Facebook posts like the one below:

{\"from\": {\"id\": \"8\", \"name\": \"Mary Pinter\"}, \"message\": \"How ARE you?\", \"c         


        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 07:10

    jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}, {"name": "Joe Schmoe"}]}, "type": "status", "id": "id_7"}"""
    
    def getTargetIds(jsonData):
        data = json.loads(jsonData)
        for dest in data['to']['data']:
            print("to_id:", dest.get('id', 'null'))
    

    Try it:

    >>> getTargetIds(jsonData)
    to_id: 1543
    to_id: null
    

    Or, if you just want to skip over values missing ids instead of printing 'null':

    def getTargetIds(jsonData):
        data = json.loads(jsonData)
        for dest in data['to']['data']:
            if 'id' in to_id:
                print("to_id:", dest['id'])
    

    So:

    >>> getTargetIds(jsonData)
    to_id: 1543
    

    Of course in real life, you probably don't want to print each id, but to store them and do something with them, but that's another issue.

提交回复
热议问题