Python: Working With JSON

Aarti
Aarti
Jan 16 · 4 min read

JSON Stands for Java Script Object Notation. JSON is the most renowned and popular data format used for representing semi structure. Don’t get caught up with a JavaScript part of the name as it is independent of any programming language, it is used for storing information in an easy and organized manner and data is in the text format when exchanged between our server and a browser.

Image for post
Image for post

Why do we use JSON over XML?

  1. JSON is less verbose, means JSON has a more compact style than XML, and it is often more readable. The lightweight approach of JSON can make significant improvements.
  2. JSON is very fast. The XML software parsing process can take a long time. JSON uses less data overall, so you can reduce the cost and increase the parsing speed.
  3. JSON structure is straightforward and it is also producing the data in a more human and machine readable format. You have an easier time mapping to domain objects, no matter what programming language you’re working on.
  4. JSON uses a map structure rather than XML’s tree structure. JSON uses key/value pair, similar to python dictionary. In some situations, key/value pairs can limit what you can do, but you get a predictable and easy-to-understand data model.

Parsing JSON:

means basically we are trying to convert a certain JSON datatype into a python datatype and then converting that python datatype back into the JSON datatype.

Let’s look at the simple example of JSON data:

What I have done is, I’ve imported the JSON package, which is a part of the standard library, then opened a string with the name as people_string now which looks like a multi-line array under which we have an object called people, now under the people we have two things which is a key and a value, so this thing basically looks like a Python Dictionary but it’s basically a JSON string under which we have several keys which are emp_name, emp_no, emp_email, emp_has_license. And then I did the conversion by typing json.loads(which basically converts my json string to the respective python datatype). JSON string decoding is done with the help of inbuilt method loads() & load() of JSON library in Python.

So, how do we know that it’s a Python datatype, that is python dictionary type? Simple, we’ll call :

print(type(data))#Output:
<class 'dict'>

Looping through the list: We are treating this as list because these are the values of the array and these array values are getting stored in the list called people.

#It'll print emp_name and emp_email 
for person in data['people']:
print(person['emp_name'],person['emp_email'])

Converting python dictionary back to JSON: Converting Python data to JSON is called an Encoding operation. Encoding is done with the help of JSON library method — dumps() method converts dictionary object of python into JSON string data format.

data = json.loads(people_string)
#This code will convert back your dict to JSON string
new_string = json.dumps(data)
print(new_string)
print(type(new_string)) #Output:
<class 'str'>

Compacting JSON: When you need to reduce the size of your JSON file, you can use compact encoding in Python. If you are not reading a file, but you only need to write JSON data into a file to use by the underlying system or application, then you can write JSON data into a file by doing compact encoding. We can write JSON data into a file by changing the JSON key-value separator. You can change JSON representation as per your needs. Using the separator argument of a json.dump() method you can specify any separator between key and value.

json.dump(people_string, write_file, separators=(',', ':'))

Format JSON code (Pretty print): used to write well-formatted code for human understanding. With the help of pretty printing, anyone can easily understand the code.There are two examples:

  1. Pretty Print JSON String:
import json

data_string = '{"firstnam":"James","surname":"Bond","mobile":["007-700-007","001-007-007-0007"]}'

#json.load method converts JSON string to Python Object
parsed = json.loads(data_string)

print json.dumps(parsed, indent=2, sort_keys=True)

Output:

{
"firstnam": "James",
"mobile": [
"007-700-007",
"001-007-007-0007"
],
"surname": "Bond"
}

2. Pretty Print JSON File:

import json

with open('jsonfile.txt') as jsonfile:
parsed = json.load(jsonfile)

print json.dumps(parsed, indent=2, sort_keys=True)

Sorting JSON: sort_keys attribute in dumps() function’s argument will sort the key in JSON in ascending order. The sort_keys argument is a Boolean attribute. When it’s true sorting is allowed otherwise not.

Thanks for giving your valuable time.

The Startup

Medium's largest active publication, followed by +771K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store