-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson_module.py
More file actions
executable file
·88 lines (66 loc) · 1.89 KB
/
json_module.py
File metadata and controls
executable file
·88 lines (66 loc) · 1.89 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import json
people_string = '''
{
"people":[
{
"name": "Johny Bairestow",
"phone": "908-976-4532",
"emails": ["bairjohny@email.com", "johnybair@email.com"],
"license_status": false
},
{
"name": "Buttler",
"phone": "123-122-2345",
"emails": ["buttlerjosh@email.com", "joshbuttler@email.com"],
"license_status": true
}
]
}
'''
#-------------------------------------------------------
# loading this json string in python as a py object
#------------------------------------------------------
# json.load method loads a file and the json.loads load a string
data = json.loads(people_string)
print(type(data))
#Json Decoders in python
'''
JSON Python
object dict
array list
string str
number(int), (float) int , float
true True
false False
null None
'''
print(data)
print(type(data['people']))
for person in data['people']:
print(person)
print(person['name'])
#Dumping the python object from the json string
del person['phone']
new_string = json.dumps(data,indent=2, sort_keys= True) #indent method for data formating
print(new_string)
# Loading the Json file in python object and back in json file
import json
with open('states.json') as file:
file_data = json.load(file)
for state in file_data['states']: #acces the state key
#print(state)
#print(state['name'], state['abbreviation'])
#deleting the key
del state['area_codes']
#print(state)
#json.dump and json.dumps method
with open('new_states.json','w') as f:
json.dump(file_data , f,indent=2)
#------------------------------------------
# Parsing the Json data from the Public API
#-------------------------------------------
import json
from urllib.request import urlopen
with urlopen("https://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?fromat=json") as response:
source = response.read()
print(source)