Reading JSON file in Python with Examples


In this article, we will see how to read a JSON file in Python with examples,

Python read JSON example
Step 1:

The first thing you need to do is import the json module,

import json
Step 2:

Now let's create a JSON object that we want to read and store it in a variable,

json_str = """[
   {
      "name":"Mike",
      "age":29,
      "city":"New York"
   },
   {
      "name":"John",
      "age":21,
      "city":"Chicago"
   },
   {
      "name":"Sam",
      "age":23,
      "city":"London"
   },
   {
      "name":"Brian",
      "age":19,
      "city":"Madrid"
   },
   {
      "name":"Danny",
      "age":27,
      "city":"New York"
   }
]"""
Step 3:

Now let's convert the JSON string to JSON Object

json_obj= json.loads(json_str)
Step 4:

Now let's read the content of JSON object, not that as we have a JSON Object of arrays, we can read it with its index starting from zero,

print(json_obj[0]["name"])
print(json_obj[0]["age"])
print(json_obj[0]["city"])

print("-----------------")
print(json_obj[1]["name"])
print(json_obj[1]["age"])
print(json_obj[1]["city"])



Full Example to Read JSON in Python:
import json

json_str = """[
   {
      "name":"Mike",
      "age":29,
      "city":"New York"
   },
   {
      "name":"John",
      "age":21,
      "city":"Chicago"
   },
   {
      "name":"Sam",
      "age":23,
      "city":"London"
   },
   {
      "name":"Brian",
      "age":19,
      "city":"Madrid"
   },
   {
      "name":"Danny",
      "age":27,
      "city":"New York"
   }
]"""

json_obj = json.loads(json_str)

print(json_obj[0]["name"])
print(json_obj[0]["age"])
print(json_obj[0]["city"])

print("-----------------")
print(json_obj[1]["name"])
print(json_obj[1]["age"])
print(json_obj[1]["city"])
Output:

Mike
29
New York
-----------------
John
21
Chicago


If you are reading JSON where you do not know the size of it and want to iterate over it, you can use a for-each loop

for element in json_obj:
  print(element['name'])
  print(element['age'])
  print(element['city'])
  print("-----------")
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.