Python中JSON數(shù)據(jù)處理的完整指南
JSON 是什么
JSON(JavaScript Object Notation)是一種輕量級數(shù)據(jù)格式,長得像 Python 的字典和列表:
{
"name": "Alice",
"age": 30,
"skills": ["Python", "Data Science"]
}
Python 自帶神器:json模塊
import json
JSON → Python(反序列化)
用 json.loads() 把 JSON 字符串變成字典:
import json
json_str = '{"name": "Alice", "age": 30, "skills": ["Python", "Data Science"]}'
data = json.loads(json_str)
print(data["name"]) # Alice
print(type(data)) # <class 'dict'>
Python → JSON(序列化)
用 json.dumps() 把 Python 對象變 JSON 字符串:
person = {
"name": "Bob",
"age": 25,
"skills": ["JavaScript", "React"]
}
json_data = json.dumps(person)
print(json_data)
優(yōu)雅打印 JSON
加 indent 一鍵格式化:
print(json.dumps(person, indent=2))
從文件讀取 JSON
with open('data.json', 'r') as file:
data = json.load(file)
print(data["name"])
把 JSON 寫進文件
with open('output.json', 'w') as file:
json.dump(person, file, indent=4)
JSON ↔ Python 類型對照表
| JSON | Python |
|---|---|
| Object | dict |
| Array | list |
| String | str |
| Number | int/float |
| true/false | True/False |
| null | None |
異常處理
解析失敗時用 try-except 捕獲:
try:
data = json.loads('{"name": "Alice", "age": }') # 非法 JSON
except json.JSONDecodeError as e:
print("解析出錯:", e)
實戰(zhàn):抓取在線 API 數(shù)據(jù)
import requests
import json
response = requests.get("https://jsonplaceholder.typicode.com/users")
users = response.json()
for user in users:
print(user['name'], '-', user['email'])
今日總結(jié)
| 任務(wù) | 函數(shù) |
|---|---|
| JSON → Python | json.loads() |
| Python → JSON | json.dumps() |
| 讀文件 | json.load() |
| 寫文件 | json.dump() |
到此這篇關(guān)于Python中JSON數(shù)據(jù)處理的完整指南的文章就介紹到這了,更多相關(guān)Python JSON數(shù)據(jù)處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python3使用mutagen進行音頻元數(shù)據(jù)處理的方法
mutagen是一個處理音頻元數(shù)據(jù)的python模塊,支持多種音頻格式,是一個純粹的python庫,僅依賴python標(biāo)準(zhǔn)庫,可在Python?3.7及以上版本運行,支持Linux、Windows?和?macOS系統(tǒng),這篇文章主要介紹了python3使用mutagen進行音頻元數(shù)據(jù)處理,需要的朋友可以參考下2022-10-10
Python如何寫入Pandas DataFrame到CSV文件
Pandas是一個功能強大的Python數(shù)據(jù)分析庫,常用于處理和分析數(shù)據(jù),CSV文件是一種廣泛使用的數(shù)據(jù)交換格式,Pandas通過to_csv方法支持將DataFrame寫入CSV文件,此方法允許用戶指定分隔符、編碼和選擇性寫入特定列等2024-09-09
python調(diào)用HEG工具批量處理MODIS數(shù)據(jù)的方法及注意事項
這篇文章主要介紹了python調(diào)用HEG工具批量處理MODIS數(shù)據(jù)的方法,本文給大家提到了注意事項,通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02
TensorFlow2.1.0安裝過程中setuptools、wrapt等相關(guān)錯誤指南
這篇文章主要介紹了TensorFlow2.1.0安裝時setuptools、wrapt等相關(guān)錯誤指南,本文通過安裝錯誤分析給出大家解決方案,感興趣的朋友跟隨小編一起看看吧2020-04-04
一篇文章帶你了解python標(biāo)準(zhǔn)庫--random模塊
這篇文章主要給大家介紹了關(guān)于Python中random模塊常用方法的使用教程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-08-08

