Site Tools


import-json

import json

import json is a Python import that serializes and deserializes JSON data. Use json.dumps() to convert Python objects to JSON strings, and json.loads() to parse JSON strings into Python dicts and lists.

Example

# Python
# description: parse JSON string, serialize to JSON
 
import json
 
# Parse JSON string
data = json.loads('{"name": "Alice", "age": 30}')
print(data['name'])  # Alice
 
# Serialize Python dict to JSON string
person = {"name": "Bob", "age": 25, "skills": ["Python", "C++"]}
json_str = json.dumps(person, indent=2)
print(json_str)
 
# Read JSON from file
with open("config.json") as f:
    config = json.load(f)
 
# Write JSON to file
with open("output.json", "w") as f:
    json.dump(config, f, indent=2)

Common functions

  • json.loads(string): parse JSON string into Python object
  • json.dumps(obj): serialize Python object to JSON string
  • json.load(file): parse JSON from file
  • json.dump(obj, file): write Python object as JSON to file
  • indent=N: pretty-print with N-space indentation
  • sort_keys=True: sort object keys in output
import-json.md · Last modified: by 127.0.0.1