Skip to content

Commit f5c6f8d

Browse files
authored
Parsing Json files in python3.
Parsing data, saving, loading into a new file.
1 parent 6754f1b commit f5c6f8d

File tree

1 file changed

+133
-0
lines changed

1 file changed

+133
-0
lines changed

Working with JSON .py

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
#!/usr/bin/env python
2+
# coding: utf-8
3+
4+
# In[1]:
5+
6+
7+
import json
8+
9+
10+
# In[48]:
11+
12+
13+
people_string =''' {
14+
"people": [{
15+
"name": "John",
16+
"age": 30,
17+
"email": "jon@gmail.com",
18+
"cars": {
19+
"car1": "Ford",
20+
"car2": "BMW",
21+
"car3": "Honda"
22+
},
23+
"children": {
24+
"c1": "Jack",
25+
"c2": "Jill"
26+
},
27+
"phone": "202-456-3214"
28+
},
29+
{
30+
"name": "Tami",
31+
"age": 28,
32+
"email": "tami@gmail.com",
33+
"cars": {
34+
"car1": "Tesla"
35+
},
36+
"children": {
37+
"c1": "Cylia",
38+
"c2": "Honey"
39+
},
40+
"phone": "232-478-4514"
41+
}
42+
]
43+
}
44+
'''
45+
46+
47+
# In[49]:
48+
49+
50+
print(type(people_string))
51+
52+
53+
# In[50]:
54+
55+
56+
type(people_string)
57+
58+
59+
# In[51]:
60+
61+
62+
data = json.loads(people_string)
63+
64+
65+
# In[52]:
66+
67+
68+
for person in data['people']:
69+
print(person['name']," ",end='')
70+
print(person['children'])
71+
72+
73+
# In[53]:
74+
75+
76+
for contact in data['people']:
77+
print(contact['name'],contact['email'],contact['phone'])
78+
79+
80+
# In[55]:
81+
82+
83+
#tidying in json format
84+
85+
tidy = json.dumps(data,indent=3,sort_keys=True)
86+
print(tidy)
87+
88+
89+
# # Loading Data in a file
90+
91+
# In[88]:
92+
93+
94+
95+
96+
with open('people.json','w') as f:
97+
for contact in data['people']:
98+
f.write(contact['name'] + " " + contact['email'] + " " + contact['phone'])
99+
f.close()
100+
101+
102+
# # Reading data from a file
103+
104+
# In[78]:
105+
106+
107+
with open('/Users/amodpanchal/Desktop/States.json') as f:
108+
data1=json.load(f)
109+
110+
#print(data1)
111+
tidy_data = json.dumps(data1,indent=2)
112+
print(tidy_data)
113+
114+
115+
# In[95]:
116+
117+
118+
for states in data1['states']:
119+
print(states['name'],states['abbreviation'])
120+
121+
122+
# In[97]:
123+
124+
125+
for states in data1['states']:
126+
print(states['abbreviation'])
127+
128+
129+
# In[ ]:
130+
131+
132+
133+

0 commit comments

Comments
 (0)