亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python中JSON數(shù)據(jù)處理的完整指南

 更新時(shí)間:2025年08月03日 09:15:28   作者:倔強(qiáng)青銅三  
本文將把目光投向現(xiàn)實(shí)世界最通用的數(shù)據(jù)語(yǔ)言——JSON,API、配置、數(shù)據(jù)庫(kù),處處都有它的身影,五分鐘掌握 Python 內(nèi)置 json 模塊,讀寫解析一氣呵成

JSON 是什么

JSON(JavaScript Object Notation)是一種輕量級(jí)數(shù)據(jù)格式,長(zhǎng)得像 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 對(duì)象變 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 寫進(jìn)文件

with open('output.json', 'w') as file:
    json.dump(person, file, indent=4)

JSON ↔ Python 類型對(duì)照表

JSONPython
Objectdict
Arraylist
Stringstr
Numberint/float
true/falseTrue/False
nullNone

異常處理

解析失敗時(shí)用 try-except 捕獲:

try:
    data = json.loads('{"name": "Alice", "age": }')  # 非法 JSON
except json.JSONDecodeError as e:
    print("解析出錯(cuò):", e)

實(shí)戰(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 → Pythonjson.loads()
Python → JSONjson.dumps()
讀文件json.load()
寫文件json.dump()

到此這篇關(guān)于Python中JSON數(shù)據(jù)處理的完整指南的文章就介紹到這了,更多相關(guān)Python JSON數(shù)據(jù)處理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論