K
K
Kris2015-04-22 19:53:08
Python
Kris, 2015-04-22 19:53:08

How to extract data from json file?

Good!
Can you please tell me how to extract data from json file?
I have an example.json file, with some content:
{ "employees": {
"employee": [
{ "id": "1",
"firstName": "Tom",
"lastName": "Cruise",
"photo ": " cdn2.gossipcenter.com/sites/default/files/imagecac... "},
{ "id": "2",
"firstName": "Maria",
"lastName": "Sharapova",
"photo" : " thewallmachine.
"lastName": "Bond",
"photo": " georgesjournal.files.wordpress.com/2012/02/007_at_... "}]}}
how do I include this file and print the "photo" value for "employee" " with id: 3?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Filimonov, 2015-04-22
@kristiks

Quite a default task, use json.loads().
https://docs.python.org/3/library/json.html

#!/usr/bin/env python

import json

path = 'example.json'

with open(path, 'r') as f:
    data = json.loads(f.read())
    for i in data['employees']['employee']:
        if i['id'] == '3':
            print(i['photo'])

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question