溫馨提示×

python怎么讀取json數(shù)組

小億
223
2023-12-16 13:39:37
欄目: 編程語言

Python中可以使用json模塊來讀取JSON數(shù)組。具體步驟如下:

  1. 導(dǎo)入json模塊。
  2. 使用open()函數(shù)打開包含JSON數(shù)據(jù)的文件,并指定文件路徑和打開模式。
  3. 使用json.load()函數(shù)加載JSON數(shù)據(jù),并將其存儲在一個變量中。
  4. 可以使用列表索引或循環(huán)等方式訪問JSON數(shù)組中的元素。

以下是一個示例代碼:

import json

# 打開包含JSON數(shù)據(jù)的文件
with open('data.json', 'r') as file:
    # 加載JSON數(shù)據(jù)
    data = json.load(file)

# 訪問JSON數(shù)組中的元素
for item in data:
    print(item)

在上面的示例中,假設(shè)有一個名為data.json的文件,其中包含一個JSON數(shù)組。通過打開文件、加載JSON數(shù)據(jù),并使用循環(huán)訪問數(shù)組中的元素,可以讀取JSON數(shù)組的內(nèi)容。

0