一、介紹
JSON是一種輕量級的數據交換格式,很多API接口返回的數據都是JSON格式。在Python中,我們可以使用json模塊來處理JSON數據,將其轉換成Python字典,然後對其進行操作。本文將圍繞使用Python對JSON數組進行循環展開,給讀者提供詳細的操作指導。
二、循環方式
1. for循環
使用for循環對JSON數組進行遍歷是最常見的方式。首先,我們需要將JSON數組轉換成Python字典,然後將字典作為for循環的迭代對象。
import json json_str = '["apple", "banana", "orange"]' json_arr = json.loads(json_str) for item in json_arr: print(item)
上面的代碼將輸出:
apple
banana
orange
2. while循環
使用while循環對JSON數組進行遍歷也是一種常見的方式。
import json json_str = '["apple", "banana", "orange"]' json_arr = json.loads(json_str) i = 0 while i < len(json_arr): print(json_arr[i]) i += 1
上面的代碼將輸出:
apple
banana
orange
3. 使用enumerate函數
使用enumerate函數可以在循環時獲取元素的索引。
import json json_str = '["apple", "banana", "orange"]' json_arr = json.loads(json_str) for i, item in enumerate(json_arr): print(i, item)
上面的代碼將輸出:
0 apple
1 banana
2 orange
三、應用場景
1. 從API中獲取JSON數據
很多API接口返回的數據都是JSON格式。使用Python對這些JSON數據進行處理,可以方便地獲取所需的信息。以下代碼演示了如何使用requests庫從API中獲取JSON數據,並使用for循環遍歷JSON數組:
import requests import json url = "https://xxxx.com/api/get_data" resp = requests.get(url) json_str = resp.text json_arr = json.loads(json_str) for item in json_arr: print("name:", item["name"]) print("age:", item["age"]) print("gender:", item["gender"])
2. 從文件中讀取JSON數據
使用Python也可以從JSON文件中讀取數據,並進行處理。下面是一個從JSON文件中讀取數據並使用for循環遍歷JSON數組的示例:
import json with open("data.json", "r") as f: json_str = f.read() json_arr = json.loads(json_str) for item in json_arr: print("name:", item["name"]) print("age:", item["age"]) print("gender:", item["gender"])
3. 將JSON數據轉換成CSV格式
使用Python對JSON數據進行處理後,可以將其轉換成CSV格式,以便進行更加靈活的數據分析。
import csv import json json_str = '[{"name": "Alice", "age": 20, "gender": "female"}, {"name": "Bob", "age": 25, "gender": "male"}, {"name": "Charlie", "age": 30, "gender": "male"}]' json_arr = json.loads(json_str) with open("data.csv", "w", newline="") as f: writer = csv.writer(f) writer.writerow(["name", "age", "gender"]) for item in json_arr: writer.writerow([item["name"], item["age"], item["gender"]]) print("Done.")
上面的代碼將生成一個名為”data.csv”的文件,其中包含JSON數據的三個字段:name、age和gender。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/247203.html