Read JSON File Using Python Code and Prompt

May 30, 2018

2 mins read

Published in

Read JSON File using Python requires importing the JSON library of Python. Before we deep dive in code let me brief you about the JSON.

JSON (Javascript Object Notation) is easy to read, write, analyze and flexible string-based format which can be used to serialized (store) and transfer between multiple application, products and between the multiple layers (Client/Server).

I have been playing around with JSON from the last 5 years in Python, Javascript, NodeJS, and JAVA.

Program to Read JSON file using Python:

1
2
3
4
5
6
import json

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

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

Create a jsonfile.txt using this JSON data. a parsed variable will become a dictionary object out of parsing JSON file. Please check in the image, how the parsed object looks like in debug mode. to understand more about “json.dump”, please visit JSON Pretty Print using Python.

Read JSON File using Python
JSON Object in Python IDE Debug
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
{
  "employees": {
    "employee": [
      {
        "id": "1",
        "firstName": "Tom",
        "lastName": "Cruise"
      },
      {
        "id": "2",
        "firstName": "Maria",
        "lastName": "Sharapova"
      },
      {
        "id": "3",
        "firstName": "James",
        "lastName": "Bond"
      }
    ]
  }
}

Read a Python File on Python Prompt.

1
2
3
4
5
6
>>> import json
>>> jsondata = json.loads(open('jsonfile.txt').read())
>>> jsondata
{u'employees': {u'employee': [{u'lastName': u'Cruise', u'id': u'1', u'firstName': u'Tom'}, 
{u'lastName': u'Sharapova', u'id': u'2', u'firstName': u'Maria'}, {u'lastName': u'Bon
d', u'id': u'3', u'firstName': u'James'}]}}

If you don’t have python setup and still want to open a JSON file to read. Please visit https://jsonformatter.org and click on an open file, select file from your system and it will open in JSON Editor.

I hope this article will help to read a JSON File using Python. Please share your views on this article.

Sharing is caring!