Python JSON

本文介绍了在 Python 中如何利用 json 模块实现 Python 对象与 json 数据之间的互转。

JSON (JavaScript 对象表示法) 是一种用于数据存储和数据交换的文本数据格式。JSON 经常使用在网络传输数据的场景中。

Python 内置了一个 json 模块,提供了将 python 对象转为 json 文本数据和将 json 文本转为 python 对象的方法。

导入 JSON 模块

Python 有一个名为 json 的内置模块,可用于处理 JSON 数据。

要使用 json 模块中的方法,请先导入 json 模块:

import json

解析 JSON

json.loads() 方法可将 JSON 字符串解析为相应的 python 对象。

从 JSON 转换为 Python 字典:

import json

# json 数据
x =  '{ "name":"John", "age":30, "city":"New York"}'

# 解析 json 数据
y = json.loads(x)

print(y["age"]) # 30

json.loads() 方法返回值的类型并不固定,根据不同的 JSON 数据类型返回不同的 python 对象类型:

JSON Python
object dict
array list
string str
number (int) int
number (real) float
TRUE TRUE
FALSE FALSE
null None
x = '{ "name":"John", "age":30 }'
y = json.loads(x)
print(y)        # {'name': 'John', 'age': 30}
print(type(y))  # <class 'dict'>

x = '[1, 2, 3]'
y = json.loads(x)
print(y)        # [1, 2, 3]
print(type(y))  # <class 'list'>

x = '"Hello World"'
y = json.loads(x)
print(y)        # Hello World
print(type(y))  # <class 'str'>

x = '1'
y = json.loads(x)
print(y)        # 1
print(type(y))  # <class 'int'>

x = '1.1'
y = json.loads(x)
print(y)        # 1.1
print(type(y))  # <class 'float'>

x = 'true'
y = json.loads(x)
print(y)        # True
print(type(y))  # <class 'bool'>

Python 对象转为 JSON

json.dumps() 方法可将 python 对象转换为 JSON 字符串。

import json

# 一个 python 字典对象
x = {
  "name": "John",
  "age": 30,
  "city": "New York"
}

# 转为 JSON
y = json.dumps(x)

# 输出结果
print(y) # {"name": "John", "age": 30, "city": "New York"}

您可以将以下类型的 Python 对象转换为 JSON 字符串:

  • 字典 dict
  • 列表 list
  • 元组 tuple
  • 字符串 str
  • 整数 int
  • 浮点数 float
  • True
  • False
  • None

将 Python 对象转换为 JSON 字符串,并打印值:

import json

print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))

当您从 Python 转换为 JSON 时,Python 对象将转换为相应的 JSON 类型:

Python JSON
dict object
list array
tuple array
str string
int number
float number
True true
False false
None null

转换包含所有数据类型的 Python 对象:

import json

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))

输出:

{"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}]}

格式化结果

上面的例子打印了一个 JSON 字符串,但它都在一行之中,没有缩进和换行符,不是很容易阅读。

json.dumps() 可以接受两个参数定义输出的格式:

  • indent 参数定义缩进的空格数
  • separators 参数使用元组定义分隔符。元组中第一个元素为 json 对象键值之间的分隔符,默认为 ,,元组第二个元素为 json 对象键和值之间的分隔符,默认为 :。使用此参数可能导致输出的结果不是标准的 json 数据。
  • sort_keys 参数来指定是否应该对结果进行排序:

使用 indent 参数定义缩进为 2 个空格:

print(json.dumps(x, indent=2))

输出:

{
  "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
    }
  ]
}

使用 separators 参数更改默认分隔符:

print(json.dumps(x, indent=2, separators=(". ", " = ")))

输出:

{
  "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
    }
  ]
}

!! 注意: 使用 separators 此参数可能导致输出的结果不是标准的 json 数据。

使用 sort_keys 参数对结果进行排序:

print(json.dumps(x, indent=2, sort_keys=True))

输出:

{
  "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
}