Skip to main content

PYTHON JSON

J
SON
import json

Some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'

Parse x:
y = json.loads(x)

The result is a Python dictionary:
print(y["age"])
30

A Python object (dict):
x = {
  "name": "John",
  "age": 30,
  "city": "New York"
}
Convert into JSON:
y = json.dumps(x)

The result is a JSON string:
print(y)
{"name": "John", "age": 30, "city": "New York"}

x = {
  "name": "John",
  "age": 30,
  "married": True,
  "divorced": False,
  "children": ("Ann","Billy"),
  "pets": None,
  "cars": [
    {"model": "BMW 230", "mpg": 27.5},
    {"model": "Ford Edge", "mpg": 24.1}
  ]
}
print(json.dumps(x, indent=2)) Use four indents to make it easier to read the result:
{
 "name": "John",
 "age": 30,
 "married": true,
 "divorced": false,
 "children": [
  "Ann",
  "Billy"
 ],
 "pets": null,
 "cars": [
  {
   "model": "BMW 230",
   "mpg": 27.5
  },
  {
   "model": "Ford Edge",
   "mpg": 24.1
  }
 ]
}
print(json.dumps(x, indent=2, separators=(" |"," --> "))) Use . and a space to separate objects, and a space, a = and a space to separate keys from their values:
{
 "name" --> "John" |
 "age" --> 30 |
 "married" --> true |
 "divorced" --> false |
 "children" --> [
  "Ann" |
  "Billy"
 ] |
 "pets" --> null |
 "cars" --> [
 {
  "model" --> "BMW 230" |
  "mpg" --> 27.5
 } |
 {
  "model" --> "Ford Edge" |
  "mpg" --> 24.1
 }
 ]
}
print(json.dumps(x, indent=2, sort_keys=True)) Sort the result alphabetically by keys:
{
 "age": 30,
 "cars": [
  {
   "model": "BMW 230",
   "mpg": 27.5
  },
  {
   "model": "Ford Edge",
   "mpg": 24.1
  }
 ],
 "children": [
  "Ann",
  "Billy"
 ],
 "divorced": false,
 "married": true,
 "name": "John",
 "pets": null
}

Comments