Parsing Json file in python

Hello all,

This is the seventh article in the series Python for Data Science. If you are new to this series, we would recommend you to read our previous articles

  1. Python for Data Science Series - Part 1
  2. Python for Data Science Series - Part 2
  3. Using Numpy in Python
  4. Using Pandas in Python
  5. Data Visualization using Matplotlib Python
  6. Parsing XML file in python


Please refer the videos below for detailed explanation on how to parse json in python.


Please refer the following notebook to understand on how to do json parsing in python.



In [4]:
import json
import os
In [2]:
main_folder_path = r"E:\openknowledgeshare.blogspot.com\Python\Outputs"
In [6]:
json_file_path = os.path.join(main_folder_path,'Sample_Json.json')
In [7]:
f = open (json_file_path, "r")
json_data = f.read()
f.close() 
In [8]:
json_data
Out[8]:
'{\n    "languages": "English",\n    "name": "Bob",\n    "numbers": [\n        2,\n        1.6,\n        null\n    ]\n}'
In [9]:
json_data = json.loads(json_data) 
In [12]:
json_data
Out[12]:
{'languages': 'English', 'name': 'Bob', 'numbers': [2, 1.6, None]}
In [11]:
json_data.keys()
Out[11]:
dict_keys(['languages', 'name', 'numbers'])
In [13]:
json_data['languages']
Out[13]:
'English'
In [14]:
dict1 = {}
dict1['a'] = [1,2,3,4,5]
dict1['b'] = [111,2,1113,42,5]
dict1['c'] = [1,21,3,4,565]
dict1['d'] = [133,2,3,24,5]
In [15]:
dict1
Out[15]:
{'a': [1, 2, 3, 4, 5],
 'b': [111, 2, 1113, 42, 5],
 'c': [1, 21, 3, 4, 565],
 'd': [133, 2, 3, 24, 5]}
In [17]:
f = open(os.path.join(main_folder_path,"OutputJSON.json"),'w')
json.dump(dict1, f)
f.close()
In [20]:
f = open(os.path.join(main_folder_path,"OutputJSON.json"),'r')
dict2 = json.loads(f.read())
f.close()
In [21]:
dict2
Out[21]:
{'a': [1, 2, 3, 4, 5],
 'b': [111, 2, 1113, 42, 5],
 'c': [1, 21, 3, 4, 565],
 'd': [133, 2, 3, 24, 5]}
In [ ]:
 

Comments

Popular posts from this blog

How to run Jupyter Notebooks in Cloud

How to download , install and configure Anaconda - Python

Project: Implementation of Label Editor