Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (12.7k points)

Let's say, I have a some set of JSON data's from the post's of Facebook like the below one:

{"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"}]}, "type": "status", "id": "id_7"}

Have a look at my code.

import json 

str = '{"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"}]}, "type": "status", "id": "id_7"}'

data = json.loads(str)

post_id = data['id']

post_type = data['type']

print(post_id)

print(post_type)

created_time = data['created_time']

updated_time = data['updated_time']

print(created_time)

print(updated_time)

if data.get('application'):

    app_id = data['application'].get('id', 0)

    print(app_id)

else:

    print('null')

#if data.get('to'):

#... This is the part I am not sure how to do

# Since it is in the form "to": {"data":[{"id":...}]}

Here, I want to print the "to_id" as 1543, else it should print 'null'

I don't know how to do this, so can anyone please help me with my query.

1 Answer

0 votes
by (26.4k points)

Code:

import json

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"}]}, "type": "status", "id": "id_7"}"""

def getTargetIds(jsonData):

    data = json.loads(jsonData)

    if 'to' not in data:

        raise ValueError("No target in given data")

    if 'data' not in data['to']:

        raise ValueError("No data for target")

    for dest in data['to']['data']:

        if 'id' not in dest:

            continue

        targetId = dest['id']

        print("to_id:", targetId)

Output:

In [9]: getTargetIds(s)

to_id: 1543

Wanna become a Python Expert? Come and join: Python training course

For more details, do check out..

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jul 15, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 5, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...