dictionary to json

作者 admin, 六月 15, 2026, 05:56 AM

« 上一篇 - 下一篇 »

admin

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)