Python – Read & Write .json

READ DATA

contacts.json

[
    {
      "NAME": "AVA",
      "PHONE": "0212345"
    },
    {
      "NAME": "CHEZTER",
      "PHONE": "0212345"
    },
    {
      "NAME": "SKY",
      "PHONE": "0212345"
    }
]

app.py

Example 1 :

import json

# open file JSON
file_json = open("contacts.json")

# parsing data JSON
data = json.loads(file_json.read())

print(data)


Example 2 :

import json

# buka file JSON
file_json = open("contacts.json")

# prsing data JSON
data = json.loads(file_json.read())

# cetak isi data JSON
print(f"Name: {data[0]['NAME']}")
print(f"Phone: {data[0]['PHONE']}")

WRITE DATA

import json

data = [
    {
      "no": "1",
      "title": "Title 1",
      "desc": "Desc 1"
    },
    {
      "no": "2",
      "title": "Title 2",
      "desc": "Desc 2"
    },
    {
      "no": "3",
      "title": "Title 3",
      "desc": "Desc 3"
    }
]

with open('contents.json', 'w') as json_file:
    json.dump(data, json_file)

Leave a Reply

Your email address will not be published. Required fields are marked *