討論區

電腦軟硬體 / iot / 3c / 技術 => python => 主題作者是: admin 於 六月 15, 2026, 05:56 AM

標題: dictionary to json
作者: admin六月 15, 2026, 05:56 AM
dictionary to json

import json

# Your Python dictionary
user_profile = {
    "name": "Alice",
    "age": 30,
    "is_member": True,
    "skills": ["Python", "Data Science"]
}
# Convert to JSON string
json_string = json.dumps(user_profile)
print(json_string)

write to file
with open("data.json", "w", encoding="utf-8") as file:
    json.dump(user_profile, file)

format json
pretty_json = json.dumps(user_profile, indent=4, sort_keys=True)
print(pretty_json)