7) d. JSON Examples




A robber has gotten hold of an API which can be used to transfer money from one account to another. This API will bypass all the security measures and will transfer the money to anyone. You want to report this to the authorities but also want to see this happening so you try to transfer money between your accoutns. THe API needs a JSON as {acc_1: [, ], money:}. Please write a module that creates this JSON and prints it on console.

1
2
3
4
5
6
7
8
9
10
11
Program:
#bank_loophole.py
import json

account_1 = 'UNIQUE_ACC_1'
account_2 = 'UNIQUE_ACC_2'
amount = 100

api_body = json.dumps({'acc_1': [account_1, account_2], 'money': amount}, indent = 4)

print(api_body)




The Dark Bruiser is the destroyer of planets and his next target is Earth. He has all the information that he needs to destroy Earth and is expected to destroy earth within a couple of weeks. Earth has a department known as ESD – Earth Safety Department whose sole purpose is to stop it from happening. They know some data is stored in E:/earth.json. You will need the data in python dictionary to be able to do any analysis on it as strings would be very difficult to handle. Read the file and print the keys on the console.

1
2
3
4
5
6
7
8
9
10
Program:
#read_earth_json.py

import json
earth_data = ''
with open('E://earth.json') as earth_file:
    earth_data = earth_file.read()

earth_dict = json.loads(earth_data)
print(earth_dict.keys())




You are working with the International Survey Bureau whose sole purpose is to save the data of each country in a json file named survey.txt. The country is a python class which consists of name and population. You have the data of the class already entered and a method which returns a python dictionary. Complete the below script to save the data. Assume the data is saved in E: drive.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Program:
#survey.py
import json

class Country:

    def __init__(self, name, pop):
        self.name = name
        self.population= pop

    def country_dict(self):
        data = {}
        data['name'] = self.name
        data['population'] = self.population
        return data

country_1 = Country('C1', '1.2M')
country_2 = Country('C2', '11.2M')

country_1_dict = country_1.country_dict()
country_2_dict = country_2.country_dict()

dict_array = [country_1_dict, country_2_dict]

with open('E://survey.txt', 'w') as survey_file:
    json.dump(dict_array, survey_file)