Working with JSON Data in Python

0
134
Working with JSON Data in Python

Introduction To JSON Data in Python

In this article, you will learn to parse, read and write JSON in python

JSON means JavaScript Object Notation. JSON was inspired by a subset of the JavaScript programming language dealing with object literal syntax.JSON easy for both humans and machines to create and understand. It is a syntax for storing and transfer the data between a server and a web application in JSON format.JSON is text, written with JavaScript object notation. A JSON text is done through a quoted-string which contains the value in key-value mapping within{ }.

Nature of JSON Data in Python Look Like:

Just show the sample of the JSON script. JSON is a very basic script to read every one.

{
	"name": "Fireblaze Technologies",
	"age": 3,
	"parentCompany":"Fireblaze AI School",
	"courses":["Python for Data Science","Data Science Master Program","Master in NLP"],
	"book":{
		"name":"The Monk Who Sold Ferrari",
		"auther":"",
		"genre":"Life Motivation",
		"best seller":"True"
		}
}

As you can see the sample JSON code, supports primitives types, like strings and numbers, as well as list and objects.

Python Support JSON

For JSON work in python, you can use the python module.

import json

Read JSON file

You can use json.load() used for reading a file containing a JSON object.

# JSON file 
f = open ('data.json', "r") 

# Reading from file 
data = json.loads(f.read())

Parse JSON in Python

The JSON module makes it easy to parse JSON string and files containing the JSON object.

Here, I used the open() function to read the JSON file.

Python Convert to JSON string

Convert a dictionary to a string using json.dumps() method.

import json

person_dict = {'name': 'Robert',
'age': 4,
'children': None
}
person_json = json.dumps(person_dict)

# Output: {"name": "Bob", "age": 12, "children": null}
print(person_json)
{"age": 4, "name": "Robert", "children": null}

You can convert many more python objects to JSON String such as,

List, dict, tuple, string, float, int, True, False, NaN.

Writing JSON to a File:

To write a JOSN file in python, just use json.dump() method.

import json

person_dict = {"name": "julia",
"languages": ["English", "Hindi"],
"married": False,
"age": 28
}

with open('sample.txt', 'w') as json_file:
  json.dump(person_dict, json_file)

Conclusion

Above JSON file, we have opened a file name sample.txt in writing mode by using ‘w’. If the file does not exist, it will be created. With the help json.dump() transform sample_dict to a JSON string.

LEAVE A REPLY

Please enter your comment!
Please enter your name here