How to write JSON file in Python Program


In this program, we will see how to write a JSON file using Python,

Program:
#
# Code2care Python Programs
# How wirite JSON file
#

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"
   }
]"""


# Writing JSON to a .json file
with open("my-json-file.json", "w") as outfile:
  outfile.write(json_str)

json_file = open("my-json-file.json", "r")

json_str = json_file.read()
json_obj = json.loads(json_str)


for element in json_obj:
  print(element['name'])
  print(element['age'])
  print(element['city'])
  print("-----------")
Content of JSON file
Content of JSON file

Comments:

  • Further comments disabled!

Topics Coverage:


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

We strongly support Gender Equality & Diversity.

Follow Us: GitHub | Facebook | Twitter | Instagram