Read json file in Python

Chia sẻ với mấy you, cách chúng ta có thể đọc 1 file json 

VD: ta có file json có định dạng cấu trúc sau:

[
    {
        "id": 123,
        "title":"Hoà Coder",
        "email":[
           
            "nguyen.thanh.hoa.ctec@gmail.com"
        ],
        "domains":[
            "https://hoanguyenit.com",
            "https://dev.hoanguyenit.com",
            "https://cv.hoanguyenit.com",
            "https://devninja.io.vn"
        ]
    },
    {
        "id": 1234,
        "title":"Skipperhoa",
        "email":[
            
            "nguyen.thanh.hoa.ctec@gmail.com"
        ],
        "domains":[
          
            "https://dev.hoanguyenit.com"
            
        ]
    }
]

Ta muốn đọc file json đó lưu vào một mảng trong python

import json
# Đọc nội dung từ file JSON
with open('domains.json', 'r') as file:
    data = json.load(file)
# Lưu dữ liệu vào một mảng mới
arr_domains = data  # Gán dữ liệu từ file JSON vào mảng mới
# In ra mảng arr_domains để kiểm tra kết quả
print(arr_domains)

Bạn có thể thử đoạn code sau. Để request một url json

Nếu bạn chưa cài thư viện thì cài : 

pip install urllib3

import urllib3
import json
url = "https://dummyjson.com/products"
http = urllib3.PoolManager()
response = http.request("GET", url)
data = response.data
products =json.loads(data)
for item in products['products']:
     print('Current Value = ',item['title'])

 

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)